Skip to content
Advertisement

List all files from a directory recursively with Java

I have this function that prints the name of all the files in a directory recursively. The problem is that my code is very slow because it has to access a remote network device with every iteration.

My plan is to first load all the files from the directory recursively and then after that go through all files with the regex to filter out all the files I don’t want. Is there a better solution?

public static printFnames(String sDir) {
    File[] faFiles = new File(sDir).listFiles();
    for (File file : faFiles) {
        if (file.getName().matches("^(.*?)")) {
            System.out.println(file.getAbsolutePath());
        }
        if (file.isDirectory()) {
            printFnames(file.getAbsolutePath());
        }
    }
}

This is just a test. Later on I’m not going to use the code like this; instead I’m going to add the path and modification date of every file which matches an advanced regex to an array.

Advertisement

Answer

Assuming this is actual production code you’ll be writing, then I suggest using the solution to this sort of thing that’s already been solved – Apache Commons IO, specifically FileUtils.listFiles(). It handles nested directories, filters (based on name, modification time, etc).

For example, for your regex:

Collection files = FileUtils.listFiles(
  dir, 
  new RegexFileFilter("^(.*?)"), 
  DirectoryFileFilter.DIRECTORY
);

This will recursively search for files matching the ^(.*?) regex, returning the results as a collection.

It’s worth noting that this will be no faster than rolling your own code, it’s doing the same thing – trawling a filesystem in Java is just slow. The difference is, the Apache Commons version will have no bugs in it.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement