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




