- Java NIO provides better performance to java application. It provides more control over I/O.
- It provides channels,buffers.
Project Structure:-
Test NIO:-
- Lets say demoFile.txt we need to read by NIO channel, then we have to use a FileInputStream.From This Stream we can read value and save it to ByteBuffer..Then we need to Flip method. Then we can append the bytes extracted form buffer to StringBuilder.
- Flip method is used to change the mode of buffer . Here it means WRITE mode to READ mode.
NioDemo.java:-
package com.sandeep.neo.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioDemo {
public static void main(String[] args) {
ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
File aTextFile = null;
FileInputStream fins = null;
try {
aTextFile =new File("demoFile.txt");
fins = new FileInputStream(aTextFile);
FileChannel fileChanel = fins.getChannel();
fileChanel.read(byteBuffer);
StringBuilder builder = new StringBuilder();
byteBuffer.flip();
while(byteBuffer.hasRemaining()){
char data = (char) byteBuffer.get();
builder.append(data);
}
System.out.println(builder);
fins.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:-
hi This is a demo file accessed by NIO.