Updated June 21, 2023
Definition of Java NIO
Java NIO is the buffer class used in the nio API. The charset API has been defined. The charset nio API is defined in the java charset package, and the selector channel API is defined in the channels package. Every nio package has its own service provider. The content is used to extend the platform of default implementers.
What is Java NIO?
In Java nio, we can also construct an alternative implementation. Java provides the IO system as nio, nothing but the new IO. It offers multiple ways of working with the standard API of IO. It is an alternative to Java IO API. It gives the channel-based and buffer-oriented approach for the operations of IO. As per the introduction of java 7 java nio system is expanded, providing enhanced support for file handling.
As per the capability of file classes of NIO, this is used in file handling. It was developed to allow Java developers to implement high-speed IO, and also we are using the native code that was custom. It moves the time-taking activities into the drained buffers and back to the OS.
Key Takeaways
- In Java, we are using IO to perform the IO operations. This operation is included in the Java IO package; this class includes all the operations.
- It is introduced from the JDK 4 to implement high-speed operations. This is an alternative to Java IO API.
Non-blocking IO
The Java non-blocking IO refers to a program that does not block the execution of other operations. We are executing the non-blocking method asynchronously. In the context of asynchronous execution, the program executes the necessary code non-sequentially, avoiding a line-by-line approach. The non-blocking code invokes the function and proceeds to the next operation without waiting for it to return.
The below example shows an example of the readFile() function demonstrating the non-blocking code as follows:
Code:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class java_nio
{
public static void main(String[] args)
{
Path p = Paths.get("G:file.txt");
String que = "Java nio";
Charset ch = Charset.forName ("ISO-8859-1");
try {
Files.write (p, que.getBytes ());
List<String> ln = Files.readAllLines (p, ch);
for (String line : ln)
{
System.out.println (line);
}
}
catch (IOException e) {
System.out.println (e);
}
}
}
Output:
Buffer-oriented Approach
It contains the two approaches. We are using java nio by using two approaches.
- Buffered-oriented approach
- Non-blocking IO operation
The java buffered-oriented approach allows us to move forth and back as per need. The buffer reads the data, and the cache also reads the data. When we require the data, it will be processed from the buffer.
The below example shows the buffer-oriented approach as follows:
Code:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.Set;
public class java_nio {
public static void main(String[] args) throws IOException {
writeFileChannel (ByteBuffer.wrap("Java nio".getBytes()));
readFileChannel();
}
public static void readFileChannel() throws IOException {
RandomAccessFile raf = new RandomAccessFile("G:file.txt", "rw");
FileChannel fc = raf.getChannel();
ByteBuffer bf = ByteBuffer.allocate(512);
Charset ch = Charset.forName("US-ASCII");
while(fc.read(bf) > 0) {
bf.rewind();
System.out.print(ch.decode(bf));
bf.flip();
}
fc.close();
raf.close();
}
public static void writeFileChannel(ByteBuffer byteBuffer) throws IOException
{
Set<StandardOpenOption> opt = new HashSet<>();
opt.add(StandardOpenOption.CREATE);
opt.add(StandardOpenOption.APPEND);
Path p = Paths.get("G:file.txt");
FileChannel fc1 = FileChannel.open(p, opt);
fc1.write(byteBuffer);
fc1.close();
}
}
Output:
Selectors of Java NIO
In Java, the selector is available to do the non-blocking operations. In Java, the nio selector is nothing but the object that monitors the multiple channels for the specified event as it performs non-blocking operations. The selectors and key of selection with selectable channels define the operations of multiplexed IO.
Selectors select the channels that are ready for Java IO operations.
The below image shows how the selector handles the channel as follows:
Components
There are mainly three components available.
- Buffers – Buffers are available in the package of primitive data types. It contains a buffer-oriented approach. Therefore, we can state that we read and write data from the buffer and then process it through the channel. Also, the buffer will act as a container for the data it held in primitive and will contain an overview of other packages of NIO. We fill the buffer using the rewind, drain, and flip methods.
- Channels – These will contain the new primitive of abstraction IO. The channel is a stream bit used to communicate from the outside world. From the specified channel, we can read data from the buffer and write it into the buffer. It performs non-blocking operations, and also channel is available for the same functions. The various channels represent the connection of different entities, and they can operate in a non-blocking manner.
- Selector – Selectors are accessible in Java to perform non-blocking actions. In Java, we refer to the object that watches many channels for a particular event as a NIO selector. It performs non-blocking operations. The selectors and key of selection with selectable channels define the operations of multiplexed IO.
The below example demonstrates the definition of the component.
Code:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class java_nio {
public static void main(String[] args) throws IOException {
…..
FileChannel fc = f.getChannel();
ByteBuffer bbf = ByteBuffer.allocate(512);
while (fc.read(bbf) > 0) {
bbf.flip();
while (bbf.hasRemaining()) {
System.out.print((char) bbf.get());
}
}
f.close();
}
}
Packages
It contains multiple packages as follows:
- nio package – This package provides an overview of all other packages. This package encapsulates the nio buffer.
- nio.channels package – This package supports selectors and channels, representing the entity’sie and IO connections.
- nio.channels.spi package – It supports the classes of service providers of the java.io.channel package.
- nio.file package – It supports the files.
- nio.file.spi package – It supports the classes of service providers of the java.io.file package.
- nio.file.attribute package – This provides support for the attributes of the file.
- nio.charset package – This package defines the character set and provides decoding and encoding operations.
- nio.charset.spi package – This package supports the service provider classes for java.nio.charset package.
Examples of Java NIO
Given below are the examples:
Example #1
In the below example, we are using the package of java.nio.channels as follows.
Code
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class java_nio {
public static void main(String[] args) throws IOException {
DatagramChannel ser = DatagramChannel.open ();
InetSocketAddress ia = new InetSocketAddress ("localhost", 8989);
ser.bind(ia);
System.out.println ("Started: " + ia);
ByteBuffer bf = ByteBuffer.allocate (1024);
SocketAddress ra = ser.receive (bf);
bf.flip ();
int lm = bf.limit ();
byte b[] = new byte[lm];
bf.get (b, 0, lm);
String msg = new String (b);
System.out.println ("Client " + ra + " sent: " + msg);
ser.send (bf, ra);
ser.close ();
}
}
Output:
Example #2
In the below example, we are using the package name java.nio.file as follows.
Code:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
public class java_nio {
public static void main(String[] args) throws IOException {
SocketChannel ser = SocketChannel.open();
SocketAddress saddr = new InetSocketAddress("localhost", 9000);
ser.connect(saddr);
Path p = Paths.get("G:file.txt");
FileChannel fc = FileChannel.open(p);
ByteBuffer bf = ByteBuffer.allocate(1024);
while(fc.read(bf) > 0) {
bf.flip();
ser.write(bf);
bf.clear();
}
fc.close();
ser.close();
}
}
Output:
Conclusion
We have defined the charset API. We define the nio API of charset in the charset package, and we define the channel of the selector API in the package of java.nio.channels. It provides a channel-based and buffer-oriented approach to IO operations.
Recommended Articles
We hope that this EDUCBA information on “Java NIO” was beneficial to you. You can view EDUCBA’s recommended articles for more information.