Java IO Tutorial - Java FileChannel.size()








Syntax

FileChannel.size() has the following syntax.

public abstract long size()   throws IOException

Example

In the following code shows how to use FileChannel.size() method.

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/*ww w . j  a  v  a 2s. com*/
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.