Java NIO (New Input/Output). It is an API (Application Programming Interface) which provides non-blocking input, output operations.it ensures high-speed in executing the operations.
Java 1.4 includes the feature.
Features:
It has the following features listed below…
- · Non-blocking I/O
- · Selectors
- · Channels and Buffers
- · Charset
- · Coders/decoders
- · Path and file operations
Program implementation:
This implementation starts from creating a text file”example.txt”
with some text.
Steps to follow:
Include the built in packages such as
java.io.RandomAccessFile,java.nio.ByteBuffer and java.nio.channels.fileChannel.
- A public class with main() function is created.
- RandomAccessFile object is created. It opens the file “example.txt” in readwrite mode.
- FileChannel object is created.it gets the channel.
- ByteBuffer object is allocated with size 48.
- Read the buffer by character by character.
- Write it to the command prompt.
- Close the file pointer.
Program:
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class jNIOEg {
public static void
main(String[] args) throws Exception {
//A file "example.txt" opens in read and write mode("rw")
RandomAccessFile raf = new RandomAccessFile("example.txt",
"rw");
//Filechannel object is created. file object gets the channel
FileChannel ch
= raf.getChannel();
//ByteBuffer object gets allocated with the size of 48
ByteBuffer
buff = ByteBuffer.allocate(48);
// channel reads the buffer and assign it to bRead variable
int bRead =
ch.read(buff);
// until bRead is not equal to -1, it continues
while (bRead
!= -1) {
buff.flip(); // make buffer ready
for read
while
(buff.hasRemaining()) {
System.out.print((char) buff.get()); // read 1 byte at a time
}
buff.clear(); // make buffer ready for writing
bRead =
ch.read(buff);
}
raf.close();
}
}
Text in the “example.txt” file is given below...
Output:
Compile and execute the above program to get the output.
C:\raji\blog>javac jNIOEg.java
C:\raji\blog>java jNIOEg
It is the time read the data
This is the sample program for implementing Java NIO. Hope
this program helps you to know about Java NIO. Keep Coding!!!
No comments:
Post a Comment