Java I/O How to - Get FileChannel from RandomAccessFile








Question

We would like to know how to get FileChannel from RandomAccessFile.

Answer

 //from ww  w .j  av a2 s . c o  m

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

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

  public static void main(String[] args) throws Exception {
    FileChannel fc = new RandomAccessFile("data.txt", "rw").getChannel();
    fc.position(fc.size());
    fc.write(ByteBuffer.wrap("Some more".getBytes()));
    fc.close();

  }
}

The code above generates the following result.