Read Mixed Data from a File through ByteBuffer in Java

Description

The following code shows how to read Mixed Data from a File through ByteBuffer.

Example


/*from   w  w w.j a v  a 2s . c  o  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.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip