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, which is nothing but the new IO. It provides multiple ways for working with the standard API of IO. It is an alternative to java IO API. It provides the channel-based and buffer-oriented approach for the operations of IO. As per the introduction of java 7 java nio system is expanded and that is providing enhanced support for file handling.
As per the capability of file classes of NIO, this is used in file handling. It is developed to allow java developers to implement high speed IO and also we are using the native code that was custom. It is moving the activities of time-taking that moving 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. The asynchronous is defined as the program does not execute the necessary code line by line. 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 data is read from the buffer, also data is read from the cache. 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 the operations of non-blocking. The selectors and key of selection with selectable channels defines the operations of multiplexed IO.
We can say that selectors are used to select the channels that were ready for the 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 is contained as buffer oriented. So, we can say that data is read and written from the buffer and then it will be processed through the channel. Also, the buffer in it will act as a container for the data it was holding it primitive and it will contain an overview of other packages of NIO. The buffer is filled by using the rewind, drained, and flipped 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 the non-blocking operations, and also channel is available for the same operations. The different entity’s connection is represented from the various channels, and they were capable to operate non-blocking.
- Selector – Selectors are accessible in Java to perform non-blocking actions. The object that watches many channels in Java for a particular event is called a nio selector. It performs non-blocking operations. The operations of multiplexed IO are defined by the selectors and key of selection with selectable channels.
The below example shows how the component is defined.
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. The nio buffer is encapsulated in this package.
- nio.channels package – This package supports selectors and channels which represent the entities connection which represents the IO connections.
- nio.channels.spi package – It supports to the classes of service providers of the java.io.channel package.
- nio.file package – It supports the files.
- nio.file.spi package – It supports to 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 also provides decoding and encoding operations.
- nio.charset.spi package – This package provides support for the service provider classes for java.nio.charset package.
Examples of Java NIO
Given below are the examples mentioned:
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
The charset API has been defined. The nio API of charset is defined in the package of charset, and the channel of selector API is defined in the package of java nio channels. It provides a channel-based and buffer-oriented approach to IO operations.
Recommended Articles
This is a guide to Java NIO. Here we discuss the introduction, what is Java NIO, selectors, components, packages and examples. You can also look at the following articles to learn more –