Java IO Tutorial - Java FileChannel.read(ByteBuffer dst)








Syntax

FileChannel.read(ByteBuffer dst) has the following syntax.

public abstract int read(ByteBuffer dst)   throws IOException

Example

In the following code shows how to use FileChannel.read(ByteBuffer dst) method.

//from ww w  .  j a v  a 2s  .  c o m
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String args[]) throws Exception {
    FileInputStream fIn = new FileInputStream("test.txt");
    FileChannel fChan = fIn.getChannel();

    long fSize = fChan.size();
    ByteBuffer mBuf = ByteBuffer.allocate((int) fSize);

    fChan.read(mBuf);
    mBuf.rewind();

    for (int i = 0; i < fSize; i++){
      System.out.print((char) mBuf.get());
    }
    fChan.close();
    fIn.close();
  }
}

The code above generates the following result.