List all files from a directory recursively with Java

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.

Leave a Comment