Java Reference
In-Depth Information
// Should not get here!
System.err.println("EOF found reading the prime string.");
break;
// Exit loop on EOF
}
System.out.printf(
"String length: %3s String: %-12s Binary Value:
%3d%n",
strLength,
((ByteBuffer)(buffers[0].flip())).asCharBuffer().toString(),
((ByteBuffer)buffers[1].flip()).getLong());
// Clear the buffers for the next read
lengthBuf.clear();
buffers[1].clear();
}
System.out.println("\nEOF reached.");
} catch(IOException e) {
e.printStackTrace();
}
}
}
ReadPrimesMixedData.java
The program reads the file that you wrote with PrimesToFile2.java in Chapter 10. You should get the
following output:
String length: 9 String: prime = 2 Binary Value: 2
String length: 9 String: prime = 3 Binary Value: 3
String length: 9 String: prime = 5 Binary Value: 5
and so on down to the end:
String length: 11 String: prime = 523 Binary Value: 523
String length: 11 String: prime = 541 Binary Value: 541
EOF reached.
How It Works
Because you use the channel read() method that reads into an array of ByteBuffer objects, you cast
the reference returned by the newByteChannel() method to type FileChannel . On each iteration of the
loop that reads the file, you first read 8 bytes into lengthBuf because this is the length of the string that
follows as a value of type double . Knowing the length of the string, you are able to create the second
buffer, buffers[0] , to accommodate the string.
The string and the binary prime value are obtained in the arguments to the printf() method:
System.out.printf(
"String length: %3s String: %-12s Binary Value:
%3d%n",
Search WWH ::




Custom Search