What is the difference between java.io and java.nio?
Quick Answer
java.io provides the original, stream-based, blocking I/O model (InputStream/OutputStream, Reader/Writer) — simple but one thread per connection/operation, blocked until data is available. java.nio (New I/O, Java 4+, expanded in Java 7 as NIO.2) adds buffer- and channel-based I/O with non-blocking and selector-based multiplexing support, letting a single thread manage many I/O channels concurrently, plus a richer, more modern file API (Path, Files) that replaced much of the old File class's awkward API.
Detailed Answer
java.io (original, since Java 1.0) is built around streams: InputStream/OutputStream for bytes, Reader/Writer for characters. It's blocking — a read call waits until data is available (or EOF), and a typical server design needs one thread per connection to handle many clients concurrently, which doesn't scale to very large numbers of simultaneous connections.
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line = br.readLine(); // blocks until a line is available
}
java.nio ("New I/O", Java 4+) introduced buffers (ByteBuffer and friends) and channels (FileChannel, SocketChannel) as a lower-level, more flexible abstraction, plus Selector-based multiplexing: a single thread can monitor many channels and only act on the ones that are actually ready for I/O, avoiding a thread-per-connection design for high-concurrency servers.
try (FileChannel channel = FileChannel.open(Path.of("file.txt"))) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
}
NIO.2 (Java 7) further modernized file system access specifically, adding Path/Paths and the Files utility class as a much richer, more consistent replacement for the old File class (which had inconsistent error reporting, no symbolic link support, and limited metadata access):
Path path = Path.of("data.txt");
List<String> lines = Files.readAllLines(path); // simple, modern convenience API
Files.copy(source, target);
Practical guidance: for everyday file reading/writing, the Files/Path convenience methods (NIO.2) are now the idiomatic default, even for simple blocking use cases — the raw channel/selector machinery mainly matters when building high-concurrency network servers that need to scale beyond a thread-per-connection model.