✅ Core Features of Java NIO (New I/O)
🔹 1. Channels
- Abstraction for reading/writing data to files, sockets, etc.
- Can be bi-directional (read + write)
- Work with Buffers, not streams
FileChannel channel = new FileInputStream("file.txt").getChannel();
🔹 2. Buffers
- Act as containers for data (like arrays)
- You read into a buffer and then process it
- Types:
ByteBuffer
, CharBuffer
, IntBuffer
, etc.
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
🔹 3. Selectors
- Allow single-threaded, non-blocking monitoring of multiple channels
- Ideal for high-performance servers
Selector selector = Selector.open();
SelectableChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
🔹 4. Non-blocking I/O
- You can configure channels to not block — operations return immediately
- Especially useful in networking (e.g.
SocketChannel
, ServerSocketChannel
)
🔹 5. FileChannel
- Allows random access to file content
- Supports memory-mapped files, positioning, reading/writing large files efficiently
🔹 6. Memory-Mapped Files
- Maps a file directly into memory, for fast access
- Great for large files or performance-critical tasks
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
🔹 7. Path and Files API (NIO.2 in Java 7)
- Classes like
Path
, Files
, and FileSystems
- Easy and fluent file operations
Path path = Paths.get("example.txt");
List<String> lines = Files.readAllLines(path);
🔹 8. WatchService (File Watcher)
- Allows you to watch directories for changes (create, delete, modify)
WatchService watcher = FileSystems.getDefault().newWatchService();
path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
🔹 9. Asynchronous I/O (NIO.2)
- Introduced in Java 7 (
AsynchronousFileChannel
, AsynchronousSocketChannel
) - Allows truly non-blocking file/network I/O with callbacks or
Future
🧠 Summary Table
Feature | Description |
---|
Channels | Bidirectional data flow |
Buffers | Data containers for channels |
Selectors | Monitor many channels with one thread |
Non-blocking I/O | Improves scalability and responsiveness |
FileChannel | Random access, fast file handling |
Memory-Mapped Files | File in memory for blazing fast access |
Path & Files API (NIO.2) | Modern file system access |
WatchService | Watch for file system changes |
Asynchronous I/O | Truly non-blocking I/O (Java 7+) |