Recursively Listing Files in a Directory in Java
Using the File class in Java IO package (java.io.File) you can recursively list all files and directories under a specific directory. There is no specific recursive search API in File class, however writing a recursive method is trivial.
Recursively Listing Files in a Directory
The following method uses a recursive method to list all files under a specific directory tree. The isFile() method is used to filter out all the directories from the list. We iterate through all folders, however we will only print the files encountered. If you are running this example on a Linux system, replace the value of the variable rootFolder with a path similar to /home/user/.
import java.io.File; public class FileFinder { public void listAllFiles(String path) { File root = new File(path); File[] list = root.listFiles(); if (list != null) { // In case of access error, list is null for (File f : list) { if (f.isDirectory()) { System.out.println(f.getAbsoluteFile()); listAllFiles(f.getAbsolutePath()); } else { System.out.println(f.getAbsoluteFile()); } } } } public static void main(String[] args) { FileFinder ff = new FileFinder(); String rootFolder = "c:\\windows"; System.out.println("List of all files under " + rootFolder); System.out.println("------------------------------------"); ff.listAllFiles(rootFolder); // this will take a while to run! } }
The return value of listFiles() will be null if the directory cannot be accessed by the Java program (for example when a folder access requires administrative privileges). If you run it on the root folder in your file system, this program will take a while to run!