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() {
super();
}/**
* 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!!!”);
return;
}crawler.directoryCrawler(directory);
}/**
* 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 {
directoryCrawler(file);}
}// 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
Filed under: JAVA Tagged: directory names, Example program to read a directory and list files in java, File directory, how to read a folder using java, how to search for a file in folder using java, Java, Java Example Programs, Java sample Programs, Java Tutorials, root directory name, sample program to how to search for a file in a folder using java, Sample program to read a directory and search for a file in java
