Java - Reading/Writing Files using channels


A FileChannel object maintains a position variable.

The read() and write() methods for FileChannel have two types: relative position read/write and absolute position read/write.

When opening a FileChannel, its position is set to 0.

As you read from a FileChannel using a relative read() method, its position is incremented by the number of bytes read.

An absolute position read from a FileChannel does not affect its position.

You can get the current value of the position by its position() method.

You can set its position using its position(int newPosition) method.

Channels are AutoCloseable and you can use a try-with-resources statement to obtain a channel.

The following code reads text from a file named

When you call the read() or write() method of a channel, it performs a relative position read/write on the buffer.

Therefore, you must call the flip() method of the buffer to read data from it after the channel writes data into the buffer.


import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] args) {
    File inputFile = new File("");
    if (!inputFile.exists()) {
      System.out.println("The input file " + inputFile.getAbsolutePath()
          + " does not exist.");
      System.out.println("Aborted the file reading process.");
      return;//www. j  a v  a 2  s .  com
    try (FileChannel fileChannel = new FileInputStream(inputFile).getChannel()) {
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      while ( > 0) {
        // Flip the buffer before we can read data from it
       while (buffer.hasRemaining()) {
          byte b = buffer.get();

          // Assuming a byte represents a character
          System.out.print((char) b);

        // Clear the buffer before next read into it
    } catch (IOException e) {


Related Topic