Files.list()
Returns a stream of the files and folders inside a folder (not nested). Files.walk() goes recursively.
Available since: Java 8
Syntax
static Stream<Path> list(Path dir) throws IOExceptionParameters
| Parameter | Type | Description |
|---|---|---|
| dir | Path | The folder to list. |
Return value
Stream<Path>A stream of paths that must be closed.
Examples
The text files of a folder in alphabetical order:
void main() throws IOException {
Path dir = Files.createDirectories(Path.of("docs"));
Files.writeString(dir.resolve("b.txt"), "");
Files.writeString(dir.resolve("a.txt"), "");
Files.writeString(dir.resolve("c.md"), "");
try (Stream<Path> files = Files.list(dir)) {
files.map(p -> p.getFileName().toString())
.filter(name -> name.endsWith(".txt"))
.sorted()
.forEach(IO::println);
}
}Output:
a.txt
b.txtNotes
The order of files is not guaranteed and depends on the system — sort them yourself. The stream keeps the folder open, so use try (...). Files.walk(dir) also goes through all nested folders.
See also
- Files.createDirectories() — Creates a folder together with all missing parent folders.
- Files.lines() — Reads a file lazily as a stream of lines, without loading it into memory.
- Path.of() — Creates a Path object — a path to a file or folder.
Related recipes
In the tutorial
- Files and paths — Working with the file system in Java — Path, Files.exists, creating folders and files, size, copying, moving, deleting and listing files.