Below is the very basic example to use the NIO in Java & hope that it will help to kick start with NIO-
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Filing {
private FileChannel fc;
private ByteBuffer bf;
public static void main(String[] args) {
new Filing().writing("Test.txt", "E:", "Hello World");
new Filing().reading("Test.txt", "E:");
}
@SuppressWarnings("static-access")
private void writing(String name, String path, String message){
try {
FileOutputStream fout = new FileOutputStream(path + "/" + name);
fc = fout.getChannel();
bf = ByteBuffer.allocate(1024);
byte[] msg = message.getBytes();
bf = bf.allocateDirect(1024);
for (int i=0; i<msg.length; i++) {
bf.put(msg[i]);
}
bf.flip();
fc.write(bf);
fc.close();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void reading(String name, String path){
try {
FileInputStream fit = new FileInputStream(path + "/" + name);
fc = fit.getChannel();
bf = ByteBuffer.allocate(1024);
fc.read(bf);
bf.flip();
while(bf.position() < bf.limit())
System.out.print((char)bf.get());
fc.close();
fit.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Filing {
private FileChannel fc;
private ByteBuffer bf;
public static void main(String[] args) {
new Filing().writing("Test.txt", "E:", "Hello World");
new Filing().reading("Test.txt", "E:");
}
@SuppressWarnings("static-access")
private void writing(String name, String path, String message){
try {
FileOutputStream fout = new FileOutputStream(path + "/" + name);
fc = fout.getChannel();
bf = ByteBuffer.allocate(1024);
byte[] msg = message.getBytes();
bf = bf.allocateDirect(1024);
for (int i=0; i<msg.length; i++) {
bf.put(msg[i]);
}
bf.flip();
fc.write(bf);
fc.close();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void reading(String name, String path){
try {
FileInputStream fit = new FileInputStream(path + "/" + name);
fc = fit.getChannel();
bf = ByteBuffer.allocate(1024);
fc.read(bf);
bf.flip();
while(bf.position() < bf.limit())
System.out.print((char)bf.get());
fc.close();
fit.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}