Java I/O How to - Save ByteBuffer to a file








Question

We would like to know how to save ByteBuffer to a file.

Answer

/*from ww w.  ja  v a2s  .co m*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  private static final int BSIZE = 1024;

  public static void main(String[] args) throws Exception {
    FileChannel fc = new FileOutputStream("data.txt").getChannel();
    fc.write(ByteBuffer.wrap("Some text ".getBytes()));
    fc.close();
  }
}