Monday, April 30, 2012

Java: File searching program

To search a particular file recursively

Let’s see a Java program which will search a particular file recursively. In this example we will provide a root path from where it will search a particular file recursively. Either you can search a file by its name or you can provide a valid regular expression.

Using this logic you can implement a file searcher program.

About the example:

Logic behind this program is very simple; it searches a root folder recursively. If the current path is a directory then it will call the same function searchFile(String path, String search) again and again till the particular node file is reached. Now if it is a node file then it will search for the String or the given regular expression.

Let’s see a simple self explanatory java code. No need to add any jar file, directly you can run below the below program and see the output. Just provide a root path and String or valid regular expression to search.

/* SearchFile.java */

import java.io.File;

public class SearchFile {

 /* path : provide root directory from where it will search recursively.
  * search : String or valid regular expression. 
  */ 
 public void searchFile(String path,String search) {
  
  File file = new File(path);
  
  //System.out.println("Searching.."+file.getAbsolutePath());
  
  if(file.isDirectory()) {
   File[] allFilesInDirectory = file.listFiles();
   
   for (File eachFile : allFilesInDirectory) {  
    searchFile(eachFile.getAbsolutePath(),search);
   }
  }
  else {
   if(file.getName().matches(search)) {
    System.out.println("File Found >> "+file.getAbsolutePath());
   }
  }
 }
 public static void main(String[] args) {
  
  SearchFile serchObj = new SearchFile();
  //It will search for a jar file in C drive
  serchObj.searchFile("C:/",".*jar");
 }

}


Note: You may get below error if your regular expression is invalid.


Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*.xlsx
^
 at java.util.regex.Pattern.error(Pattern.java:1713)
 at java.util.regex.Pattern.sequence(Pattern.java:1878)
 at java.util.regex.Pattern.expr(Pattern.java:1752)
 at java.util.regex.Pattern.compile(Pattern.java:1460)
 at java.util.regex.Pattern.(Pattern.java:1133)
 at java.util.regex.Pattern.compile(Pattern.java:823)
 at java.util.regex.Pattern.matches(Pattern.java:928)
 at java.lang.String.matches(String.java:2090)