Java Reference
In-Depth Information
set to the capacity. This is precisely what you want when you have worked partway through the data in an
input buffer and you want to add some more data from the file. Compacting the buffer sets the position and
limit such that the buffer is ready to receive more data. The next read operation using the buffer adds data at
the end of what was left in the buffer.
TRY IT OUT: Reading into a Large Buffer
Here is a new version of the previous example that reads data into a large buffer:
import java.nio.file.*;
import java.nio.channels.ReadableByteChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
public class ReadPrimesMixedData2 {
public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("primes.txt");
if(!Files.exists(file)) {
System.out.println(file + " does not exist. Terminating
program.");
System.exit(1);
}
try(ReadableByteChannel inCh = Files.newByteChannel(file)) {
ByteBuffer buf = ByteBuffer.allocateDirect(256);
buf.position(buf.limit());
// Set the position for the loop
operation
int strLength = 0;
// Stores the string length
byte[] strChars = null;
// Array to hold the bytes for
the string
while(true) {
if(buf.remaining() < 8) {
// Verify enough bytes for
string length
if(inCh.read(buf.compact()) == -1)
break;
// EOF reached
buf.flip();
}
strLength = (int)buf.getDouble(); // Get the string length
// Verify enough bytes for complete string
if(buf.remaining() < 2*strLength) {
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found reading the prime string.");
break;
// EOF reached
}
Search WWH ::




Custom Search