Monday, February 27, 2017

How to list files in a directory with Java 8

Here is how it can be done with older Java versions:

File folder = new File("path/to/dir");
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
    if (files[i].getName().endsWith("txt")) {
        System.out.println("File found: " 
                + files[i].getName());
    }
}
You might also use for-each loop which would make it nicer. Now we have streams in Java 8:

Files.list(Paths.get("path/to/dir"))
    .filter(file -> file.toString().endsWith("txt"))
    .forEach(file -> {
        System.out.println("File found: " + file);
    });

It doesn't look shorter (although you can write it in one line, and still be able to read it), but no loops and ifs.

There is one disadvantage in the approach with streams (or, at least one). If something throws a checked exception in forEach(), then you'll need to catch it there. You can't add a "throws" statement to the method which contains this code - the Java compiler will complain about that.

Enjoy.