Lesson 25: File I/O with java.nio
26 Jul 2026 1 min Swarnil Singhai
Modern Java I/O (java.nio.file) reads/writes files with fewer lines and better error semantics than the old java.io streams.
Real-time example
A report generator writes a daily CSV of sales, then a separate job reads it back for archiving — both in a few lines.
Path report = Path.of("sales-2026-07-10.csv");
List<String> rows = List.of("id,amount", "1,499.00", "2,999.00");
Files.write(report, rows);
List<String> readBack = Files.readAllLines(report);
readBack.forEach(System.out::println);
What's happening
Files.write/readAllLines handle opening, buffering, and closing the file for you — no manual try/finally needed.
For huge files, prefer Files.lines() (a lazy Stream) over readAllLines() to avoid loading everything into memory.
Advertisement