FileChannel position

In this chapter you will learn:

  1. How to get FileChannel position for reading and writing
  2. How to set new position for a FileChannel

Get FileChannel position for reading and writing

abstract long position() Returns this channel's file position.

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
// java 2s . 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());
  }
}

Set new position for a FileChannel

abstract FileChannel position(long newPosition) sets this channel's file position.

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/* ja va2s. c  o m*/
public class Main {
  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();

  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to lock a FileChannel
  2. Attempts to acquire an exclusive lock on this channel's file