Reading from a Channel with a ByteBuffer - Java File Path IO

Java examples for File Path IO:ByteBuffer

Description

Reading from a Channel with a ByteBuffer

Demo Code

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

public class Main {
  public static void main(String[] argv) {
    try {//  ww  w .  j  a  va2s  .  c  o  m
      // Obtain a channel
      ReadableByteChannel channel = new FileInputStream("infile").getChannel();

      // Create a direct ByteBuffer; see also Creating a ByteBuffer
      ByteBuffer buf = ByteBuffer.allocateDirect(10);

      int numRead = 0;
      while (numRead >= 0) {
        buf.rewind();

        // Read bytes from the channel
        numRead = channel.read(buf);

        buf.rewind();

        for (int i = 0; i < numRead; i++) {
          byte b = buf.get();
        }
      }
    } catch (Exception e) {
    }
  }
}

Related Tutorials