adam bien's blog

Listing Directory Contents with JDK 1.7 and NIO.2 📎


import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;


    public static List<String> fileList(String directory) {
        List<String> fileNames = new ArrayList<>();
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(directory))) {
            for (Path path : directoryStream) {
                fileNames.add(path.toString());
            }
        } catch (IOException ex) {}
        return fileNames;
    }

The JDK 1.0 version is a bit shorter:


String[] directories = new File("dir").list();

However: Because the DirectoryStream is a "lazy" Iterable the NIO.2 version is better suitable for directories with lots of contents. Also the JDK 1.7 version supports out-of-the-box filtering.