Search directories recursively for file in Java

Here’s an example to show you how to search a file named “post.php” from directory “/Users/mkyong/websites” and all its subdirectories recursively.

FileSearch.java
package com.mkyong;
 
import java.io.File;
import java.util.ArrayList;
import java.util.List;
 
public class FileSearch {
 
  private String fileNameToSearch;
  private List<String> result = new ArrayList<String>();
 
  public String getFileNameToSearch() {
	return fileNameToSearch;
  }
 
  public void setFileNameToSearch(String fileNameToSearch) {
	this.fileNameToSearch = fileNameToSearch;
  }
 
  public List<String> getResult() {
	return result;
  }
 
  public static void main(String[] args) {
 
	FileSearch fileSearch = new FileSearch();
 
        //try different directory and filename :)
	fileSearch.searchDirectory(new File("/Users/mkyong/websites"), "post.php");
 
	int count = fileSearch.getResult().size();
	if(count ==0){
	    System.out.println("\nNo result found!");
	}else{
	    System.out.println("\nFound " + count + " result!\n");
	    for (String matched : fileSearch.getResult()){
		System.out.println("Found : " + matched);
	    }
	}
  }
 
  public void searchDirectory(File directory, String fileNameToSearch) {
 
	setFileNameToSearch(fileNameToSearch);
 
	if (directory.isDirectory()) {
	    search(directory);
	} else {
	    System.out.println(directory.getAbsoluteFile() + " is not a directory!");
	}
 
  }
 
  private void search(File file) {
 
	if (file.isDirectory()) {
	  System.out.println("Searching directory ... " + file.getAbsoluteFile());
 
            //do you have permission to read this directory?	
	    if (file.canRead()) {
		for (File temp : file.listFiles()) {
		    if (temp.isDirectory()) {
			search(temp);
		    } else {
			if (getFileNameToSearch().equals(temp.getName().toLowerCase())) {			
			    result.add(temp.getAbsoluteFile().toString());
		    }
 
		}
	    }
 
	 } else {
		System.out.println(file.getAbsoluteFile() + "Permission Denied");
	 }
      }
 
  }
 
}

Output

Searching directory ... /Users/mkyong/websites
Searching directory ... /Users/mkyong/websites/wp-admin
Searching directory ... /Users/mkyong/websites/wp-admin/css
Searching directory ... /Users/mkyong/websites/wp-admin/images
Searching directory ... /Users/mkyong/websites/wp-admin/images/screenshots
Searching directory ... /Users/mkyong/websites/wp-admin/includes
Searching directory ... /Users/mkyong/websites/wp-admin/js
Searching directory ... /Users/mkyong/websites/wp-admin/maint
Searching directory ... /Users/mkyong/websites/wp-admin/network
Searching directory ... /Users/mkyong/websites/wp-admin/user
Searching directory ... /Users/mkyong/websites/wp-content
Searching directory ... /Users/mkyong/websites/wp-content/plugins
//long list, omitted.
 
Found 3 result!
 
Found : /Users/mkyong/websites/wp-admin/includes/post.php
Found : /Users/mkyong/websites/wp-admin/post.php
Found : /Users/mkyong/websites/wp-includes/post.php
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Anil

    Hi,
    Can you please help me on this –
    I am using the same code as posted by mkyoung, its working fine from main method. Even I am searching file from shared network path like – \\XXXXX\YYYYY\JARS

    But when I am integrating same code in my struts 1.2 application and trying to rearch same file name in same directory(\\XXXXX\YYYYY\JARS) I am getting message –
    \\XXXXX\YYYYY\JARS is not a directory!

    I am using RAD7.5 IBM WAS 7.0

    Regards,
    Anil

  • Abhishek

    /* I am searching for files whose name starts with “Claim” in the folder D:/Abhishek/src/.
    But it is showing no file is found. Kindly help. */

    package com.abhishek;

    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;

    public class RecursiveFileSearch {

    private String fileNameToSearch;
    private List result = new ArrayList();

    public String getFileNameToSearch() {
    return fileNameToSearch;
    }

    public void setFileNameToSearch(String fileNameToSearch) {
    this.fileNameToSearch = fileNameToSearch;
    }

    public List getResult() {
    return result;
    }

    public static void main(String[] args) {

    RecursiveFileSearch fileSearch = new RecursiveFileSearch();
    fileSearch.searchDirectory(new File(“D:/Abhishek/src”), “Claim”);

    int count = fileSearch.getResult().size();
    if(count ==0){
    System.out.println(“\n N0 RESULT”);
    }else{
    System.out.println(“\nFound ” + count + ” result!\n”);
    for (String matched : fileSearch.getResult()){
    System.out.println(“Found : ” + matched);
    }
    }
    }

    public void searchDirectory(File directory, String fileNameToSearch) {

    setFileNameToSearch(fileNameToSearch);

    if (directory.isDirectory()) {
    search(directory);
    } else {
    System.out.println(directory.getAbsoluteFile() + ” is not a directory!”);
    }

    }

    private void search(File file) {

    if (file.isDirectory()) {
    System.out.println(“Searching directory —-> ” + file.getAbsoluteFile());
    if (file.canRead()) {
    for (File temp : file.listFiles()) {
    if (temp.isDirectory()) {
    search(temp);
    } else {
    if (getFileNameToSearch().equals(temp.getName().toLowerCase())) {
    result.add(temp.getAbsoluteFile().toString());
    }

    }
    }

    } else {
    System.out.println(file.getAbsoluteFile() + “Permission Denied”);
    }
    }

    }
    }

  • Swapnil
    hiee sir...
     
     
    //////////////////////////code to open a notepad
    if (resultText.contentEquals(&quot;open notepad&quot;) == true) {
            try {
    Process pbrowser = Runtime.getRuntime().exec(&quot;cmd /c start notepad&quot;);
                 }
            catch (IOException e) {
                    e.printStackTrace();
            }}
     
    //after opening dis notepad....suppose v feel to save it or print
    it......so normally v use a keyboard shorkut ie ctrl+s .....iv used
    it...but how to tell jvm d meaning of ctrl+s through a code.....dats
    my doubt
     
     
    if (resultText.contentEquals(&quot;save notepad&quot;) == true) {
            try {
    Process pbrowser = Runtime.getRuntime().exec(&quot;ctrl+s&quot;);   //doubt in
    dis line &quot;ctrl+s&quot;
                 }
            catch (IOException e) {
                    e.printStackTrace();
            }}
    ............................thnks in adv sir....ane help v b greatly
    appreciated Sir!!!!!!
  • Gops

    I want to list all pdf or .doc file.Kindly help me

  • Gops

    Is it possible to search with wildcards like *.pdf

  • [email protected]

    Such an amazing article.

    You have been great help Mr. Daft.

    thanks.

  • Raghavendra

    hi MKYONG, is there any possibility to call c++ graphics program in JSP just as applet embedded in a jsp page??
    Plzz help me!!

  • http://www.journaldev.com Pankaj

    Thanks for the program but I think it’s easy to do using unix find command.

    find . -name post.php