Java IO Tutorial - Java FileChannel.position(long newPosition)








Syntax

FileChannel.position(long newPosition) has the following syntax.

public abstract FileChannel position(long newPosition)    throws IOException

Example

In the following code shows how to use FileChannel.position(long newPosition) method.

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
//from   ww  w. ja  v  a2s  .c  om
public class Main {
  public static void main(String[] argv) throws IOException {
    RandomAccessFile randomAccessFile = new RandomAccessFile("test.dat", "r");

    randomAccessFile.seek(1000);

    FileChannel fileChannel = randomAccessFile.getChannel();

    // This will print "1000"
    System.out.println("file pos: " + fileChannel.position());

    randomAccessFile.seek(500);

    // This will print "500"
    System.out.println("file pos: " + fileChannel.position());

    fileChannel.position(200);

    // This will print "200"
    System.out.println("file pos: " + randomAccessFile.getFilePointer());
  }
}

The code above generates the following result.