Lesson 36 / 38
Reading & Writing Files
Read and write files with the modern java.nio.file API, fall back to Scanner for quick line-by-line reads, and always close resources with try-with-resources.
java.io vs java.nio.file
The classic java.io package (FileReader, BufferedReader) still works everywhere. Since Java 7, java.nio.file — Path and Files — offers a friendlier, more modern API for most everyday file tasks and is the recommended starting point.
Reading with Files
Files.readString and Files.readAllLines are one-liners for small-to-medium files. For huge files, stream lines instead of loading everything into memory.
Path path = Path.of("notes.txt");
String whole = Files.readString(path);
List<String> lines = Files.readAllLines(path);
try (var stream = Files.lines(path)) {
stream.filter(l -> !l.isBlank()).forEach(System.out::println);
}Writing & Scanner for files
Files.writeString writes (or creates) a file in one call. Scanner can also wrap a File directly — handy for reading structured, token-by-token input the same way you read from the console.
Files.writeString(Path.of("out.txt"), "hello\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
try (Scanner sc = new Scanner(new File("scores.txt"))) {
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
}
} catch (FileNotFoundException e) {
throw new UncheckedIOException(e);
}Always close, always handle IOException
File handles are a limited OS resource — always open them in a try-with-resources. Almost every file operation throws the checked IOException, so the compiler will remind you if you forget.