Java FileChannel read to ByteBuffer

Description

Java FileChannel read to ByteBuffer

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");
    try (FileChannel fileChannel = new FileInputStream(inputFile).getChannel()) {
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      while (fileChannel.read(buffer) > 0) {
        // Flip the buffer before reading data
        buffer.flip();//from  w w  w  . j  a v a 2s. com
        while (buffer.hasRemaining()) {
          byte b = buffer.get();
          System.out.print(b);
        }
        // Clear the buffer before read
        buffer.clear();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related