Writing a file using Channel and Buffer
suggest changeTo write data to a file using Channel
we need to have the following steps:
- First, we need to get an object of
FileOutputStream
- Acquire
FileChannel
calling thegetChannel()
method from theFileOutputStream
- Create a
ByteBuffer
and then fill it with data - Then we have to call the
flip()
method of theByteBuffer
and pass it as an argument of thewrite()
method of theFileChannel
- Once we are done writing, we have to close the resource
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();
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents