import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileNIO {
public static void main(String[] args) throws IOException {
try {
FileOutputStream fout = new FileOutputStream("nio.txt");
FileChannel fc = fout.getChannel();
ByteBuffer bb = ByteBuffer.allocate(10);
bb.clear();
for (int i = 0; i < 10; i++) {
System.out.println("space left in the buffer "+bb.limit());
System.out.println("next element where the data need to be put :"+bb.position());
bb.put((byte) 'A');
}
System.out.println("space left in the buffer "+bb.limit());
System.out.println("next element where the data need to be put :"+bb.position());
bb.flip();
fc.write(bb);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
will print the following output
space left in the buffer 10
next element where the data need to be put :0
space left in the buffer 10
next element where the data need to be put :1
space left in the buffer 10
next element where the data need to be put :2
space left in the buffer 10
next element where the data need to be put :3
space left in the buffer 10
next element where the data need to be put :4
space left in the buffer 10
next element where the data need to be put :5
space left in the buffer 10
next element where the data need to be put :6
space left in the buffer 10
next element where the data need to be put :7
space left in the buffer 10
next element where the data need to be put :8
space left in the buffer 10
next element where the data need to be put :9
space left in the buffer 10
next element where the data need to be put :10