I\'ve used the old, obsolete java.io.File.listFiles() for too long.
The performance is not so good. It is:
The Java 7's java.nio.file package can be used to enhance performance.
The DirectoryStream
To get the instance representing a given Path, the Files.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 with DirectoryStream
Path folder = Paths.get("...");
try (DirectoryStream stream = Files.newDirectoryStream(folder)) {
for (Path entry : stream) {
// Process the entry
}
} catch (IOException ex) {
// An I/O problem has occurred
}
The DirectoryStream.Filter
Since it's a @FunctionalInterface, starting with Java 8 you could implement it with a lambda expression, overriding the Filter
Path folder = Paths.get("...");
try (DirectoryStream stream = Files.newDirectoryStream(folder, "*.txt")) {
for (Path entry : stream) {
// The entry can only be a text file
}
} catch (IOException ex) {
// An I/O problem has occurred
}
Path folder = Paths.get("...");
try (DirectoryStream stream = Files.newDirectoryStream(folder,
entry -> Files.isDirectory(entry))) {
for (Path entry : stream) {
// The entry can only be a directory
}
} catch (IOException ex) {
// An I/O problem has occurred
}