How to search a file in a directory in java

JavaServer Side ProgrammingProgramming

The List() method of the File class returns a String array containing the names of all the files and directories in the path represented by the current (File) object.

In order to search for a file you need to compare the name of each file in the directory to the name of the required file using the equals() method.

Example

Live Demo

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");
      }
   }
}

Output

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

The String[] list(FilenameFilter filter) method of a File class returns a String array containing the names of all the files and directories in the path represented by the current (File) object. But the retuned array contains the filenames which are filtered based on the specified filter. The FilenameFilter is an interface in Java with a single method.

accept(File dir, String name)

To search for a file name you need to implement a FilenameFilter that matches the name of the desired file.

Example

Live Demo

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");
      }
   }
}

Output

File Found

raja
Published on 08-Feb-2021 11:08:46
Advertisements