Junior — Middle
Can you explain what Java NIO is and how it differs from the standard input-output mechanisms in Java?
sobes.tech AI
Answer from AI
Java NIO (New Input/Output) is a set of APIs introduced in Java 1.4 for more efficient input-output operations. Unlike standard streams (java.io), which operate in a blocking manner and are oriented towards sequential access, NIO provides non-blocking input-output and lower-level control over operations.
Main differences:
- Buffers and channels: NIO uses buffers (ByteBuffer, etc.) for data storage and channels for reading/writing, which allows for more efficient data handling.
- Non-blocking mode: You can perform input-output operations without blocking the thread, useful for scalable server applications.
- Selectors: Allow a single thread to monitor multiple channels, simplifying the handling of many connections.
Example of reading a file using NIO:
Path path = Paths.get("file.txt");
try (SeekableByteChannel channel = Files.newByteChannel(path)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (channel.read(buffer) > 0) {
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}