File क्लास का String[] list(FilenameFilter filter) मेथड वर्तमान (File) ऑब्जेक्ट द्वारा दर्शाए गए पथ में सभी फाइलों और डायरेक्टरीज के नामों वाला एक String सरणी वापस करता है। लेकिन रिटर्न की गई सरणी में फाइल नाम होते हैं जो निर्दिष्ट फिल्टर के आधार पर फिल्टर किए जाते हैं। FilenameFilter जावा में एक इंटरफेस है जिसमें एक सिंगल मेथड होता है।
accept(File dir, String name)
एक्सटेंशन के आधार पर फाइल नाम प्राप्त करने के लिए इस इंटरफेस को ऐसे इम्प्लीमेंट करें और फाइल क्लास के ऊपर निर्दिष्ट list() मेथड को इसका ऑब्जेक्ट पास करें।
मान लें कि हमारे पास D डायरेक्टरी में ExampleDirectory नामक एक फोल्डर है जिसमें 7 फाइलें और 2 डायरेक्टरीज हैं -

उदाहरण
निम्नलिखित जावा प्रोग्राम पथ D:\\ExampleDirectory में टेक्स्ट फाइलों और JPEG फाइलों के नामों को अलग-अलग प्रिंट करता है।
import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class Sample{ public static void main(String args[]) throws IOException { //डायरेक्टरी के लिए File ऑब्जेक्ट बनाना File directoryPath = new File("D:\\ExampleDirectory"); //jpg फाइलों के लिए फिल्टर बनाना FilenameFilter jpgFilefilter = new FilenameFilter(){ public boolean accept(File dir, String name) { String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".jpg")) { return true; } else { return false; } } }; String imageFilesList[] = directoryPath.list(jpgFilefilter); System.out.println("List of the jpeg files in the specified directory:"); for(String fileName : imageFilesList) { System.out.println(fileName); } } }आउटपुट
List of the jpeg files in the specified directory: cassandra_logo.jpg cat.jpg coffeescript_logo.jpg javafx_logo.jpg
उदाहरण
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; public class Example { public static void main(String[] args) throws IOException { Stream<Path> path = Files.walk(Paths.get("D:\\ExampleDirectory")); path = path.filter(var -> var.toString().endsWith(".jpg")); path.forEach(System.out::println); } }आउटपुट
List of the jpeg files in the specified directory: cassandra_logo.jpg cat.jpg coffeescript_logo.jpg javafx_logo.jpg