# NIO.2 File I/O — Advanced Java

Source: https://www.geekswithgeeks.com/en/advanced-java/adv-nio

> 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.

```java
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.

```java
try (Stream<Path> paths = Files.walk(Path.of("src"))) {
    long javaFiles = paths
        .filter(p -> p.toString().endsWith(".java"))
        .count();
}
```
