C

Core Java tutorial for beginners

Clean • Professional

Java NIO and NIO.2 Explained with Examples

3 minute

Java NIO and NIO.2

Java NIO (New I/O) was introduced in Java 1.4, and later enhanced as NIO.2 in Java 7. It provides faster, scalable, non-blocking I/O and a modern file API compared to traditional java.io.

What is Java NIO?

Java NIO (New I/O) was introduced in Java 1.4 to overcome the limitations of traditional Java I/O (streams). It provides faster, non-blocking, and buffer-oriented data processing.


Why NIO?

  • Non-blocking I/O
  • Efficient for large files
  • Uses Channels + Buffers (faster than Streams)
  • Supports memory-mapped files
  • Better file operations

Core Components of NIO

learn code with durgesh images

A) Buffer

  • Temporary memory block used to read/write data.
  • Types: ByteBuffer, CharBuffer, IntBuffer, etc.

B) Channel

  • A bidirectional communication channel.
  • Reads/writes data from/to Buffers.
  • Types:
    • FileChannel
    • SocketChannel
    • ServerSocketChannel
    • DatagramChannel

C) Selector

  • Used for non-blocking multiplexed I/O.
  • Single thread can manage multiple channels.

FileChannel Example (Read File)

FileInputStream fis = new FileInputStream("data.txt");
FileChannel channel = fis.getChannel();

ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);

buffer.flip();
while (buffer.hasRemaining()) {
    System.out.print((char) buffer.get());
}

channel.close();
fis.close();

Memory-Mapped Files (Super Fast File Access)

RandomAccessFile file = new RandomAccessFile("data.txt", "r");
FileChannel channel = file.getChannel();

MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

while (buffer.hasRemaining()) {
    System.out.print((char) buffer.get());
}

Java NIO.2 (Java 7+)

NIO.2 is an upgraded version introduced in Java 7, primarily for file handling, directories, and file system operations.


Key NIO.2 Components

learn code with durgesh images

A) Path Interface

Represents a file path.

Path path = Paths.get("files/data.txt");

B) Files Class

Contains 100+ utility methods for file operations:

  • read / write
  • create / delete
  • move / copy
  • check existence
  • get file properties

Common Files Class Operations

Check file exists

Files.exists(path);

Read all lines

List<String> lines = Files.readAllLines(path);

Write to file

Files.write(path, "Hello Java".getBytes());

Copy file

Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);

Move file

Files.move(oldPath, newPath);

Delete file

Files.delete(path);

Directory Stream Example

Path dir = Paths.get("logs");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path file : stream) {
        System.out.println(file.getFileName());
    }
}

Walking File Tree (Search / Operations on All Files)

Files.walk(Paths.get("src"))
     .forEach(System.out::println);

WatchService (Folder Monitoring)

Used to detect:

  • file creation
  • modification
  • deletion
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("data");

path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
    System.out.println("New File: " + event.context());
}

Difference Between Java NIO and NIO.2

FeatureJava NIO (Java 1.4)Java NIO.2 (Java 7)
PurposeHigh-performance I/O (non-blocking, scalable)Modern, simplified file handling and filesystem operations
Main ConceptBuffers, Channels, SelectorsPath, Paths, Files, FileVisitor, WatchService
Focus AreaNetwork I/O, buffer-based processingFile system operations (copy, move, delete, read, write, monitoring)
File HandlingLimited & complex using FileChannelVery easy using Files class
Path HandlingNot availableIntroduced Path interface (replaces File)
Directory TraversalManual, difficultSimple with Files.walk() and FileVisitor
File MonitoringNot supportedSupported via WatchService
Copy / Move FilesRequires manual byte operationsOne line: Files.copy(), Files.move()
Delete FilesUsing File API or channel workaroundFiles.delete() (clean, reliable)
Exception HandlingTraditional I/O exceptionsEnhanced exceptions (e.g., FileAlreadyExistsException)
Symbolic LinksNo direct supportFull support in NIO.2
Use CaseHigh-performance server networkingModern file operations & directory management

 

Article 0 of 0