Java Notes
Complete guide to Java NIO (New I/O) — Path, Files, Channels, Buffers, non-blocking I/O, WatchService, and modern file operations that replace traditional java.io approaches.
What is NIO?
NIO (New I/O) was introduced in Java 1.4 (enhanced in Java 7 as NIO.2) as a modern alternative to traditional java.io. It provides:
java.nio.file.Path— replacement forjava.io.Filejava.nio.file.Files— utility methods for file operations- Channels & Buffers — for high-performance I/O
- Non-blocking I/O — for scalable network applications
- WatchService — file system monitoring
| Traditional I/O (java.io) | NIO (java.nio): |
| File | Path |
| FileInputStream | Files.newInputStream() |
| FileOutputStream | Files.newOutputStream() |
| FileReader/Writer | Files.newBufferedReader/Writer() |
| File.listFiles() | Files.list(), Files.walk() |
| File.delete() | Files.delete() |
Path — Modern File Path Handling
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| path1 | src/main/java/App.java |
| Filename | App.java |
| Parent | src/main/java |
| Root | null |
| Name count | 4 |
| Base | /home/user |
| Relative | documents/file.txt |
| Resolved | /home/user/documents/file.txt |
| Before | ./data/../config/app.properties |
| After | config/app.properties |
| From | /home/user/docs |
| To | /home/user/photos/vacation |
| Relative | ../../photos/vacation |
Files — Powerful File Operations
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Walking Directory Trees
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Channels and Buffers
NIO introduces a channel-based I/O model using Buffers:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| ✓ Written via FileChannel | 48 bytes |
| ✓ Read via FileChannel | Hello from NIO Channels! This is efficient I/O. |
| Capacity | 20 |
| Position | 0 |
| Limit | 20 |
| Position | 12 |
| Position | 0 |
| Limit | 12 |
| Read int | 42 |
| Read double | 3.14 |
WatchService — File System Monitoring
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
NIO vs Traditional I/O Comparison
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Common Mistakes
1. Not closing streams from Files methods
// ❌ BAD: Stream is never closed (resource leak!)
Files.walk(Path.of(".")).forEach(System.out::println);
// ✅ GOOD: Use try-with-resources
try (Stream<Path> paths = Files.walk(Path.of("."))) {
paths.forEach(System.out::println);
}2. Using readAllBytes on huge files
// ❌ BAD: Loads entire 2GB file into memory!
byte[] data = Files.readAllBytes(Path.of("huge_file.dat"));
// ✅ GOOD: Stream line by line
try (Stream<String> lines = Files.lines(Path.of("huge_file.txt"))) {
lines.filter(l -> l.contains("ERROR")).forEach(System.out::println);
}3. Forgetting to flip ByteBuffer
Interview Questions
Q1: What is the difference between java.io.File and java.nio.file.Path?
Answer: File is a legacy class (Java 1.0) representing a file path. Path (Java 7) is its modern replacement offering: better error handling (exceptions with reasons vs booleans), symbolic link support, file system independence, and integration with the Files utility class. New code should always use Path.
Q2: What are Channels and Buffers in NIO?
Answer: Channels are bidirectional connections to I/O sources (files, sockets). Buffers are containers that hold data being transferred. Data flows: Channel → Buffer (read) or Buffer → Channel (write). This is more efficient than stream-based I/O because channels can use OS-level optimizations like DMA transfers.
Q3: What is the difference between blocking and non-blocking I/O?
Answer: Blocking I/O: the thread waits (blocks) until the operation completes. Non-blocking I/O (NIO): the thread can continue doing other work — it checks if data is available without waiting. This allows one thread to manage many connections (key for scalable servers).
Q4: What is WatchService used for?
Answer: WatchService monitors file system changes (create, modify, delete events) in a directory. Use cases: hot-reloading config files, auto-compiling changed source files, sync tools (like Dropbox), log file monitoring.
Q5: What are the advantages of Files.copy() over manual stream copying?
Answer: Files.copy() uses OS-level operations (like sendfile on Linux) that can transfer data without copying through user space. It handles atomic operations, preserves file attributes, supports options like REPLACE_EXISTING and COPY_ATTRIBUTES, and provides clear exceptions on failure.
Q6: Explain ByteBuffer's flip() method.
Answer: flip() prepares a buffer for reading after writing. It sets limit = position (marks the end of written data) and position = 0 (starts reading from the beginning). Without flip, you'd try to read from the current position (end of data) and get nothing.
Continue the lesson path