Interview question
What are NIO (New I/O) Channels and Buffers? How are they different from traditional I/O? NIO Channels और Buffers क्या हैं? Traditional I/O से कैसे अलग हैं?
Answer
NIO (java.nio) provides channels and buffers for faster, non-blocking file I/O. Channels are two-way, support multiplexing, and work with buffers for bulk data transfer. Better performance for large files.
import java.io.*;
import java.nio.file.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
public class NIODemo {
public static void main(String[] args) {
// Copy file using NIO (faster)
copyFileUsingNIO('source.txt', 'destination.txt');
}
public static void copyFileUsingNIO(String source, String dest) {
try (FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(dest);
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (inChannel.read(buffer) > 0) {
buffer.flip();
outChannel.write(buffer);
buffer.clear();
}
System.out.println('File copied using NIO');
} catch (IOException e) {
e.printStackTrace();
}
}
}
// NIO vs Traditional I/O
// Traditional: Stream-based, blocking, single direction
// NIO: Channel-based, non-blocking, bidirectional
// Using Files utility class (Java 7+)
public class FilesAPIDemo {
public static void main(String[] args) {
try {
// Read all lines
List<String> lines = Files.readAllLines(
Paths.get('file.txt'));
// Write lines
Files.write(Paths.get('output.txt'),
'New content'.getBytes());
// Copy file
Files.copy(Paths.get('source.txt'),
Paths.get('dest.txt'));
// Walk directory
Files.walk(Paths.get('.'))
.filter(Files::isRegularFile)
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// ByteBuffer operations
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put(new byte[]{65, 66, 67}); // Write to buffer
buffer.flip(); // Switch to read mode
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear(); // Clear for next useNIO (New I/O):
Traditional I/O (java.io):
- Stream-based
- Blocking operations
- Single direction (input/output)
- Character/Byte streams
- Slower for large files
NIO (java.nio):
- Channel-based
- Non-blocking operations
- Bidirectional
- Buffers + Channels
- Faster for large files
- Multiplexing support
Usage:
// NIO File Copy (faster)
try (FileChannel inChannel = new FileInputStream('src').getChannel();
FileChannel outChannel = new FileOutputStream('dst').getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (inChannel.read(buffer) > 0) {
buffer.flip();
outChannel.write(buffer);
buffer.clear();
}
}
Files API (Java 7+):
Files.copy(source, destination);Was this answer clear?