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

19 comments on “Search directories recursively for file in Java

  1. Hi @mkyong – Please replace equals with equalsIgnoreCase in below code:

    if (getFileNameToSearch().equals(temp.getName().toLowerCase()))

    Reply
  2. Great work in Java. Your examples really help starters

    Reply
  3. Hey there! Is there a code that does the same but on SFTP not locally?

    Reply
  4. this code checks for a file with specific name. I have to search for a folder with specific name in this similar manner

    Reply
  5. how to write a program to get list of images of size 2 mb and name containing “lumi” from the given directory

    Reply
  6. My requirement is to build a program that reads all the log files from server and saves in separate folder in local disk .I am able to read all the log files but through trycatch handler but would like to use loops instead.need help.

    try {
    CookieManager cManager1 = new CookieManager();
    CookieHandler.setDefault(cManager1);
    // Establish a URL and open a connection to it. Set it to output mode.
    URLObj = new URL(“https://bhbdsfd”);

    connect = URLObj.openConnection();
    //connect.setDoOutput(true);
    String userpass1 = “1243dfd”+ “:” + “fgfh$”;
    String basicAuth1 = “Basic ” + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass1.getBytes());
    connect.setRequestProperty (“Authorization”, basicAuth1);

    File file1 = new File(“C:/Users/dsfd/Downloads/LOGFILE.TXT”);

    BufferedInputStream bis1 = new BufferedInputStream(connect.getInputStream());

    @SuppressWarnings(“resource”)
    BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(file1));
    int i1;
    while ((i1 = bis1.read()) != -1) {
    bos.write(i1);
    }
    bos.flush();
    bis1.close();

    }
    catch (MalformedInputException malformedInputException) {
    malformedInputException.printStackTrace();
    } catch (IOException ioException) {
    ioException.printStackTrace();
    }

    Reply
  7. hi thank you so much , but if the file start with capital letter it doesn’t work

    Reply
  8. NullPointerException.. check exceptions with try..catch block

    Reply
  9. Hi,

    You should change one line in this..

    if (getFileNameToSearch().equals(temp.getName().toLowerCase())) {

    to

    if (getFileNameToSearch().toLowerCase().equals(temp.getName().toLowerCase())) {

    I have added .toLowerCase() to getFileNameToSearch()..

    Regards,
    Niraj

    Reply
    1. Or just remove the “toLowerCase” on both sides, in case your operating system is case-sensitive.

      Reply
  10. 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

    Reply
  11. /* 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”);
    }
    }

    }
    }

    Reply
  12. hiee sir...
    
    
    //////////////////////////code to open a notepad
    if (resultText.contentEquals("open notepad") == true) {
            try {
    Process pbrowser = Runtime.getRuntime().exec("cmd /c start notepad");
                 }
            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("save notepad") == true) {
            try {
    Process pbrowser = Runtime.getRuntime().exec("ctrl+s");   //doubt in
    dis line "ctrl+s"
                 }
            catch (IOException e) {
                    e.printStackTrace();
            }}
    ............................thnks in adv sir....ane help v b greatly
    appreciated Sir!!!!!!
    
    Reply
  13. hi MKYONG, is there any possibility to call c++ graphics program in JSP just as applet embedded in a jsp page??
    Plzz help me!!

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

    find . -name post.php

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *