← Back to Chapters

Java NIO Introduction

⚡ Java NIO Introduction

? Quick Overview

Java NIO (New Input/Output) is an advanced I/O API introduced in Java 1.4 that provides high-performance, non-blocking I/O operations. It is designed for scalable applications such as servers, file systems, and network programs.

? Key Concepts

  • Buffer-based data handling
  • Channels instead of streams
  • Non-blocking I/O support
  • Selectors for multiplexing
  • Better performance for large data

? Syntax / Theory

Java NIO works mainly with three core components:

  • Buffer – Container for data
  • Channel – Reads/Writes data
  • Selector – Monitors multiple channels

? Code Example(s)

? View Code Example
// Java NIO example using ByteBuffer
import java.nio.ByteBuffer;

public class NioIntro {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put((byte) 65);
buffer.flip();
while (buffer.hasRemaining()) {
System.out.println((char) buffer.get());
}
}
}

? Live Output / Explanation

Output

The program prints:

A

The buffer stores byte data, switches to read mode using flip(), and then reads the value.

? Interactive Buffer Simulator Capacity: 8
 
Pos: 0 Limit: 8 Mode: Write

Start by putting data into the buffer.

✅ Tips & Best Practices

  • Always flip the buffer before reading
  • Reuse buffers to improve performance
  • Use NIO for large-scale or network apps

? Try It Yourself

  • Create a buffer of size 20 and store characters
  • Experiment with clear() and rewind()
  • Explore FileChannel for file reading