Example Java Program to Search Files in a Folder

Below Java Program lists the file names and directory names available in given folder. To do this implementation , we can get the files list in a folder using File class available in Java API. Iterate the files one by one and write the file name on to console.

If it is identified as a directory instead of a file, then iterate the process as mentioned in directoryCrawler() method in the below class.

package in.javatutorials;

import java.io.File;

* @author malliktalksjava
* Search for the files in a folder and prints all file details.
public class FolderCrawler {

private static String directoryPath = “D://test”;

* Creating constructor
public FolderCrawler() {

* main method
* @param ags
public static void main(String[] args) {
FolderCrawler crawler = new FolderCrawler();

File directory = new File(directoryPath);

if (directory == null || !directory.exists()) {
System.out.println(“Directory doesn’t exists!!!”);


* Gets all the file and directories and prints accordingly
* @param directory
* Directory path where it should search
public void directoryCrawler(File directory) {

// Get List of files in folder and print
File[] filesAndDirs = directory.listFiles();

// Print the root directory name
System.out.println(“-” + directory.getName());

// Iterate the list of files, if it is identified as not a file call
// directoryCrawler method to list all the files in that directory.
for (File file : filesAndDirs) {

if (file.isFile()) {
System.out.println(” |-” + file.getName());
} else {

}// end of for

}// End of directory Crawler


Other Useful Links:

Javac/Java searching algorithm for other classes

Example program to reverse a Number in Java

How to find count of duplicates in a List

Threads Interview questions in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.