java.nio Package in Java

The java.nio package provides a set of APIs for efficient non-blocking input/output (I/O) operations. Java NIO, short for New I/O, was introduced in Java 1.4 as an alternative to the traditional I/O package (java.io). The NIO API is based on the buffer-oriented approach, which means that data is read and written to and from buffers. Buffers are efficient containers for data that can be easily manipulated and transferred.

The NIO package is divided into the following subpackages:

  • java.nio.channels: This subpackage defines classes that represent channels, which are used to perform I/O operations on underlying resources such as files, sockets, and network interfaces.
  • java.nio.charset: This subpackage defines classes for encoding and decoding data between different character sets.
  • java.nio.file: This subpackage defines classes for accessing and managing files and file systems.

The java.nio package is used in a wide variety of applications, including:

  • Web servers
  • Network applications
  • File transfer applications
  • Database applications
  • Real-time systems

Benefits of using the java.nio package

There are several benefits to using the java.nio package:

  • Performance: The NIO API is designed for high performance. It uses efficient buffering and non-blocking I/O operations to minimize overhead.
  • Scalability: The NIO API is scalable to handle large numbers of concurrent I/O operations.
  • Flexibility: The NIO API is flexible and can be used to implement a wide variety of I/O scenarios.

Example of using the java.nio.channels package

The following example shows how to use the java.nio.channels package to read data from a file:

import java.nio.channels.FileChannel;
import java.io.FileInputStream;

public class Main {
        public static void main(String[] args) throws Exception {
		// Create a FileChannel for the file to be read. The file is located in Desktop location. 
		FileChannel channel = new FileInputStream(
				"C:\\Users\\codersathi\\Desktop\\hello.txt").getChannel();

		// Create a ByteBuffer to store the data read from the file.
		ByteBuffer buffer = ByteBuffer.allocate(1024);// You can adjust the buffer size as
														// needed

		while ((channel.read(buffer)) != -1) {
			buffer.flip(); // Flip the buffer to read data

			while (buffer.hasRemaining()) {
				System.out.print((char) buffer.get()); // Print the characters
			}
			/*
			 * Clear the buffer for the next read. If we don't clear it, then the loop
			 * will continue forever. You can check it first with buffer.clear() and later
			 * without buffer.clear().
			 */
			 buffer.clear();
		}

		// Close the channel.
		channel.close();
	}
}

This example will read the contents of the file hello.txt and print them to the console.