Java I/O lives in java.io (classic streams) and java.nio.file (modern Paths API). Prefer Files.readString / writeString for simple text in Java 11+.
Try-with-resources
try (BufferedReader reader = Files.newBufferedReader(path)) {
String line = reader.readLine();
}
Auto-closes resources—implements AutoCloseable.
Playground note
The sandbox may restrict filesystem paths. In production, validate paths, handle IOException, and never trust user-supplied filenames for writes.
Important interview questions and answers
- Q: try-with-resources benefit?
A: Guaranteed close even on exception—prevents descriptor leaks. - Q: nio.file vs java.io?
A: NIO.2 Paths API is simpler for files; streams still used for sockets and legacy APIs.
Self-check
- Which interface enables try-with-resources?
- Why catch IOException separately from RuntimeException?