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

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Roshan Bawane
Guest
Roshan Bawane

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

Azmi Ara
Guest
Azmi Ara
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 =… Read more »
meryy
Guest
meryy

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

Carlos Jesus Arancibia Taborga
Guest
Carlos Jesus Arancibia Taborga

NullPointerException.. check exceptions with try..catch block

niraj patel
Guest
niraj patel

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

transXpro
Guest
transXpro

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

Anil
Guest
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
Guest
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 + ”… Read more »
Swapnil
Guest
Swapnil
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!!!!!!
Gops
Guest
Gops

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

Gops
Guest
Gops

Is it possible to search with wildcards like *.pdf

crpy@phsex.com
Guest
crpy@phsex.com

Such an amazing article.

You have been great help Mr. Daft.

thanks.

Raghavendra
Guest
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!!

Pankaj
Guest
Pankaj

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

find . -name post.php

abhishek kumar
Guest
abhishek kumar

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