Java Reference
In-Depth Information
try {
ByteBuffer lengthBuf = ByteBuffer.allocate(8);
int strLength = 0; // Stores the string length
ByteBuffer buf = null; // Stores a reference to the second byte buffer
byte[] strChars = null; // A reference to an array to hold the string
while(true) {
if(inChannel.read(lengthBuf) == -1) // Read the string length,
break; // if its EOF exit the loop
lengthBuf.flip();
// Extract the length and convert to int
strLength = (int)lengthBuf.getDouble();
// Buffer for the string & the prime
buf = ByteBuffer.allocate(strLength+8);
if(inChannel.read(buf) == -1) { // Read the string & binary prime value
assert false; // Should not get here!
break; // Exit loop on EOF
}
buf.flip();
strChars = new byte[strLength]; // Create the array for the string
buf.get(strChars); // Extract string & binary prime value
System.out.println("String length: " + strChars.length+ " String: " +
new String(strChars) + " Binary value: " +
buf.getLong());
lengthBuf.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);
}
}
Don't forget that you need to specify the -source 1.4 option when you compile code that includes
assertions and the -enableassertions option when you execute it. You should get the 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
Search WWH ::




Custom Search