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.

/* */


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);
  if(file.isDirectory()) {
   File[] allFilesInDirectory = file.listFiles();
   for (File eachFile : allFilesInDirectory) {  
  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


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
 at java.util.regex.Pattern.error(
 at java.util.regex.Pattern.sequence(
 at java.util.regex.Pattern.expr(
 at java.util.regex.Pattern.compile(
 at java.util.regex.Pattern.(
 at java.util.regex.Pattern.compile(
 at java.util.regex.Pattern.matches(
 at java.lang.String.matches(