I've used the old, obsolete java.io.File.listFiles()
for too long.
The performance is not so good. It is:
- Expensive, since it creates a new
File
object for each entry. - Slow, because you have to wait for the array to be completed before starting the processing.
- Very bad, especially if you need to work only on subset of the content.
What are the alternatives?
The Java 7's
java.nio.file
package can be used to enhance performance.Iterators
The
DirectoryStream<T>
interface can be used to iterate over a directory without preloading its content into memory. While the old API creates an array of all filenames in the folder, the new approach loads each filename (or limited size group of cached filenames) when it encounters it during iteration.To get the instance representing a given
Path
, theFiles.newDirectoryStream(Path)
static method can be invoked. I suggest you to use the try-with-resources statement to properly close the stream, but if you can't, remember to do it manually at the end withDirectoryStream<T>.close()
.Filters
The
DirectoryStream.Filter<T>
interface can be used to skip groups of entries during iteration.Since it's a
@FunctionalInterface
, starting with Java 8 you could implement it with a lambda expression, overriding theFilter<T>.accept(T)
method which decides if the given directory entry should be accepted or filtered. Then you would use theFiles.newDirectoryStream(Path, DirectoryStream.Filter<? super Path>)
static method with the newly created instance. Or you might prefer theFiles.newDirectoryStream(Path, String)
static method instead, which can be used for simple filename matching.