Lesson 14 / 38
NIO.2 File I/O
Work with files the modern way using Path and the Files helper class — readString, lines as a lazy Stream, walk, copy — all inside try-with-resources.
Path and Files
Path represents a location; Files has static operations — readString, writeString, readAllLines, lines (a lazy Stream<String>), walk, copy, exists. They throw IOException, so wrap in try-with-resources when a stream is returned.
Path p = Path.of("data", "log.txt");
try (Stream<String> lines = Files.lines(p)) {
long errors = lines.filter(l -> l.contains("ERROR")).count();
}Walking a directory tree
Files.walk returns a lazy Stream<Path> over an entire subtree — combine it with normal stream operations, and always close it since it holds an open directory handle.
try (Stream<Path> paths = Files.walk(Path.of("src"))) {
long javaFiles = paths
.filter(p -> p.toString().endsWith(".java"))
.count();
}