Directory Crawler or Directory Parser in Java

Directory Crawler or Directory Parser is a program that can crawl into each and every folder of a given directory and list out the files present in it. This can be used for various purposes like,
– File search
– File parsing
– Report generation, etc.


Java Directory Crawler or Directory Parser Program.


import java.io.File;
import java.util.List;
import java.util.ArrayList;
public class DirectoryCrawler{
public static void main(String [] args){
//Starting directory for parsing
File aStartingDir = new File("C:/Program Files");
directoryCrawler(aStartingDir);
System.out.println("Parsing complete");
}
public static void directoryCrawler(File aStartingDir){
File[] filesAndDirs = aStartingDir.listFiles();
List<File> dir = new ArrayList<File>();
//Current Directory being traversed
System.out.
println("------------------------------------------------");
System.out.println(aStartingDir.toString());
System.out.
println("------------------------------------------------");
//List all files in directory
for(File file:filesAndDirs){
if (file.isFile()) {
//Display file names
System.out.println(file.getPath());
}
else {
//Add first level directory to a list
dir.add(file);
}
}
if(dir.isEmpty())
return;
else {
/*Traverse directory structure recursively
by calling directory crawler */
for(File file:dir){
directoryCrawler(file);
}
}
}
}

Enjoy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *