File क्लास का List() मेथड वर्तमान (File) ऑब्जेक्ट द्वारा दर्शाए गए पथ में सभी फाइलों और डायरेक्टरीज के नामों वाला एक String सरणी वापस करता है।
फाइल खोजने के लिए आपको डायरेक्टरी में प्रत्येक फाइल के नाम की तुलना equals() मेथड का उपयोग करके आवश्यक फाइल के नाम से करनी होगी।
उदाहरण
import java.io.File; import java.util.Arrays; import java.util.Scanner; public class Example { public static void main(String[] argv) throws Exception { System.out.println("Enter the directory path: "); Scanner sc = new Scanner(System.in); String pathStr = sc.next(); System.out.println("Enter the desired file name: "); String file = sc.next(); System.out.println(file); File dir = new File(pathStr); String[] list = dir.list(); System.out.println(Arrays.toString(list)); boolean flag = false; for (int i = 0; i < list.length; i++) { if(file.equals(list[i])){ flag = true; } } if(flag){ System.out.println("File Found"); }else{ System.out.println("File Not Found"); } } }आउटपुट
Enter the directory path: D:\\ExampleDirectory Enter the desired file name: demo2.pdf demo2.pdf [demo1.pdf, demo2.pdf, sample directory1, sample directory2, sample directory3, sample directory4, sample_jpeg1.jpg, sample_jpeg2.jpg, test1.docx, test2.docx] File Found
String[] list(FilenameFilter filter) मेथड File क्लास का एक String सरणी वापस करता है जिसमें वर्तमान (File) ऑब्जेक्ट द्वारा दर्शाए गए पथ में सभी फाइलों और डायरेक्टरीज के नाम होते हैं। लेकिन रिटर्न की गई सरणी में फाइल नाम होते हैं जो निर्दिष्ट फिल्टर के आधार पर फिल्टर किए जाते हैं। FilenameFilter जावा में एक इंटरफेस है जिसमें एक सिंगल मेथड होता है।
accept(File dir, String name)
फाइल नाम खोजने के लिए आपको एक FilenameFilter इम्प्लीमेंट करना होगा जो वांछित फाइल के नाम से मेल खाता हो।
उदाहरण
import java.io.File; import java.io.FilenameFilter; public class Example { public static void main(String[] argv) throws Exception { File dir = new File("D:\\ExampleDirectory"); FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.equalsIgnoreCase("demo1.pdf"); } }; String[] files = dir.list(filter); if (files == null) { System.out.println("File Not Found"); }else { System.out.println("File Found"); } } }आउटपुट
File Found