Java Reference
In-Depth Information
If we wanted to collect the primes into an array, the form of get() method that transfers values to an
array is more efficient than writing a loop to transfer them one at a time, but we have to be careful. Let's
try it out in an example to see why.
Try It Out - Reading a Binary File
We will choose to read the primes six at a time into an array. Here's the program:
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadPrimes {
public static void main(String[] args) {
File aFile = new File("C:/Beg Java Stuff/primes.bin");
FileInputStream inFile = null;
try {
inFile = new FileInputStream(aFile);
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel inChannel = inFile.getChannel();
final int PRIMECOUNT = 6;
ByteBuffer buf = ByteBuffer.allocate(8*PRIMECOUNT);
long[] primes = new long[PRIMECOUNT];
try {
while(inChannel.read(buf) != -1) {
((ByteBuffer)(buf.flip())).asLongBuffer().get(primes);
System.out.println();
for(int i = 0 ; i<primes.length ; i++)
System.out.print(" " + primes[i]);
buf.clear(); // Clear the buffer for the next read
}
System.out.println("\nEOF reached.");
inFile.close(); // Close the file and the channel
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
We get a whole lot of prime values, six to a line, then, when we almost have them all displayed, we
suddenly get the output:
Search WWH ::




Custom Search