Java I/O How to - Read Mixed Data from a File through ByteBuffer








Question

We would like to know how to read Mixed Data from a File through ByteBuffer.

Answer

/*from   w  ww .j  a  v  a2 s  .  co m*/
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    File aFile = new File("main.java");
    FileInputStream inFile = new FileInputStream(aFile);
    FileChannel inChannel = inFile.getChannel();
    ByteBuffer lengthBuf = ByteBuffer.allocate(8);
    while (true) {
      if (inChannel.read(lengthBuf) == -1) {
        break;
      }
      lengthBuf.flip();
      int strLength = (int) lengthBuf.getDouble();
      ByteBuffer buf = ByteBuffer.allocate(2 * strLength + 8);
      if (inChannel.read(buf) == -1) {
        break;
      }
      buf.flip();
      byte[] strChars = new byte[2 * strLength];
      buf.get(strChars);
      System.out.println(strLength);
      System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
      System.out.println(buf.getLong());
      lengthBuf.clear();
    }
    inFile.close();
  }
}

The code above generates the following result.