Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to list files in a folder

Short answer

Suppose there is a docs folder with readme.md, notes.txt and a nested img folder. Files.list() returns its contents without going into nested folders:

void main() throws IOException {
    try (Stream<Path> paths = Files.list(Path.of("docs"))) {
        paths.map(p -> p.getFileName().toString()).sorted().forEach(IO::println);
    }
}

Output:

img
notes.txt
readme.md

The order of Files.list() is not guaranteed, so the result is sorted.

Only files of a certain type

Filter regular files with the ending you need:

void main() throws IOException {
    try (var paths = Files.list(Path.of("docs"))) {
        paths.filter(Files::isRegularFile)
                .filter(p -> p.toString().endsWith(".txt"))
                .forEach(p -> IO.println(p.getFileName()));
    }
}

Output:

notes.txt

Including nested folders

Files.walk() traverses the folder tree recursively:

void main() throws IOException {
    Path root = Path.of("docs");
    try (var paths = Files.walk(root)) {
        paths.filter(Files::isRegularFile)
                .map(p -> root.relativize(p).toString().replace('\\', '/'))
                .sorted()
                .forEach(IO::println);
    }
}

Output:

img/logo.png
notes.txt
readme.md

replace('\\', '/') makes the paths look the same on Windows and Linux.

Common mistake

Not closing the Files.list() or Files.walk() stream. They keep the folder open — always use a try-with-resources. And for a folder that does not exist, both methods throw:

void main() throws IOException {
    try (var paths = Files.list(Path.of("no-such-folder"))) {
        paths.forEach(IO::println);
    }
}

Output:

Exception in thread "main" java.nio.file.NoSuchFileException: no-such-folder

Functions used in this recipe

  • Files.list() — Returns a stream of the files and folders inside a folder (not nested). Files.walk() goes recursively.
  • Path.of() — Creates a Path object — a path to a file or folder.

Thanks for reading!

Donate to the site — we work hard for you.