File I/O:
*Writing a file using Channel and Buffer
To write data to a file using Channel we need to have the following steps:
FileOutputStream
FileChannel calling the getChannel() method from the FileOutputStream
ByteBuffer and then fill it with data
flip() method of the ByteBuffer and pass it as an argument of the write() method of the FileChannel
import java.io.*;
import java.nio.*;
public class FileChannelWrite {
public static void main(String[] args) {
File outputFile = new File("hello.txt");
String text = "I love Bangladesh.";
try {
FileOutputStream fos = new FileOutputStream(outputFile);
FileChannel fileChannel = fos.getChannel();
byte[] bytes = text.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(bytes);
fileChannel.write(buffer);
fileChannel.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}