Writing a file using Channel and Buffer

suggest change

To write data to a file using a Channel we need to have the following steps:

  1. First, we need to get an object of FileOutputStream
  2. Acquire a FileChannel by calling the getChannel() method from the FileOutputStream
  3. Create a ByteBuffer and then fill it with data
  4. Pass the ByteBuffer to the write() method of the FileChannel. ByteBuffer.wrap is already ready to be read. If you filled the buffer with put, call flip() before write()
  5. Once we are done writing, we have to close the resource
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
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();
  }
 }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents