Java ByteBuffer flip before reading

Description

Java ByteBuffer flip before reading

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  va2  s.  c  o  m
        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