Skip to content
AgileLogics
4 min read

File I/O

Prerequisites: Streams

java.nio.file.Files offers simple, modern methods for common file tasks:

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

Path file = Path.of("notes.txt");

try {
    Files.writeString(file, "Hello, file!");
    String content = Files.readString(file);
    System.out.println(content);
} catch (IOException e) {
    System.out.println("File error: " + e.getMessage());
}

Common mistakes

  • Forgetting file operations throw a checked IOException — the compiler forces you to either catch it or add throws IOException to the enclosing method.