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
Hey there! Is there a code that does the same but on SFTP not locally?
hi thank you so much , but if the file start with capital letter it doesn’t work
Nice, thanks for commenting your code lol
Hi @mkyong – Please replace equals with equalsIgnoreCase in below code:
if (getFileNameToSearch().equals(temp.getName().toLowerCase()))
Great work in Java. Your examples really help starters
this code checks for a file with specific name. I have to search for a folder with specific name in this similar manner
how to write a program to get list of images of size 2 mb and name containing “lumi” from the given directory
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();
}
NullPointerException.. check exceptions with try..catch block
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
Or just remove the “toLowerCase” on both sides, in case your operating system is case-sensitive.
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
/* 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”);
}
}
}
}
I want to list all pdf or .doc file.Kindly help me
Is it possible to search with wildcards like *.pdf
Such an amazing article.
You have been great help Mr. Daft.
thanks.
hi MKYONG, is there any possibility to call c++ graphics program in JSP just as applet embedded in a jsp page??
Plzz help me!!
Thanks for the program but I think it’s easy to do using unix find command.
find . -name post.php