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();
}
}