Friday, 6 December 2013

Java Code To Search Directories Recursively For A File

Here is the Java Code to search for a file recursively through the code.
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileSearch {
     
     static List<String> result = new ArrayList<String>();
     
     public static void main(String[] args) {
          String dirc = "C:\\Users\\naved.alam\\workspace\\Test";
          String fName = "FileSearch.java";
          FileSearch.search(new File(dirc),fName);
          int size = result.size();
          if(size ==0){
               System.out.println("\nNo File found.");
          }else{
               System.out.println("\nFound " + size + " File:");
               for (String matched : result){
                    System.out.println("File : " + matched);
               }
          }
     }

     private static void search(File directory,String fileName) {
          if (directory.isDirectory()) {
               System.out.println("Searching directory..." + directory.getAbsoluteFile());
               //Check for permission
               if (directory.canRead()) {
                    for (File temp : directory.listFiles()) {
                         if (temp.isDirectory()) 
                              search(temp,fileName);
                         else if (fileName.equals(temp.getName()))      
                                   result.add(temp.getAbsoluteFile().toString());
                    }

               } 
               else 
                    System.out.println(directory.getAbsoluteFile() + ": Permission Denied");
          }
     }
}
A sample run is shown below:
Searching directory...C:\Users\naved.alam\workspace\Test
Searching directory...C:\Users\naved.alam\workspace\Test\.settings
Searching directory...C:\Users\naved.alam\workspace\Test\backup
Searching directory...C:\Users\naved.alam\workspace\Test\bin
Searching directory...C:\Users\naved.alam\workspace\Test\bin\com
Searching directory...C:\Users\naved.alam\workspace\Test\bin\com\example
Searching directory...C:\Users\naved.alam\workspace\Test\src
Searching directory...C:\Users\naved.alam\workspace\Test\src\com
Searching directory...C:\Users\naved.alam\workspace\Test\src\com\example

Found 2 File:
File : C:\Users\naved.alam\workspace\Test\backup\FileSearch.java
File : C:\Users\naved.alam\workspace\Test\src\com\example\FileSearch.java
Above code can be modified to search for a file matching certain pattern or expression and can be use to integrate advance file searching functionality in an application.

No comments:

Post a Comment