Java IO Tutorial

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 Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
19 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Hani
5 years ago

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

meryy
8 years ago

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

Drew
1 year ago

Nice, thanks for commenting your code lol

Vivek Tiwari
3 years ago

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

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

Azmat Ali
4 years ago

Great work in Java. Your examples really help starters

abhishek kumar
5 years ago

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

Roshan Bawane
6 years ago

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

Azmi Ara
6 years ago

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();
}

Carlos Jesus Arancibia Taborga
9 years ago

NullPointerException.. check exceptions with try..catch block

niraj patel
10 years ago

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
9 years ago
Reply to  niraj patel

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

Anil
10 years ago

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
10 years ago

/* 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
11 years ago
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
11 years ago

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

Gops
11 years ago

Is it possible to search with wildcards like *.pdf

11 years ago

Such an amazing article.

You have been great help Mr. Daft.

thanks.

Raghavendra
11 years ago

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
11 years ago

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

find . -name post.php