Java - Reading/Writing Files using channels

Introduction

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 Main.java.

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.

Demo

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] args) {
    File inputFile = new File("Main.java");
    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 (fileChannel.read(buffer) > 0) {
        // Flip the buffer before we can read data from it
        buffer.flip();
       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
        buffer.clear();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result

Related Topic