Read a Binary File in Java

Description

The following code shows how to read a Binary File.

Example


/* ww  w  .  ja va  2s  .  c om*/
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("C:/test.bin");
    FileInputStream inFile = new FileInputStream(aFile);
    FileChannel inChannel = inFile.getChannel();
    final int PRIMECOUNT = 6;
    ByteBuffer buf = ByteBuffer.allocate(8 * PRIMECOUNT);
    long[] primes = new long[PRIMECOUNT];
    while (inChannel.read(buf) != -1) {
      ((ByteBuffer) (buf.flip())).asLongBuffer().get(primes);
      for (long prime : primes) {
        System.out.printf("%10d", prime);
      }
      buf.clear();
    }
    inFile.close();
  }
}




















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