Java Reference
In-Depth Information
primeStr = "prime = " + primes[primesWritten];
if ((buf.position() + 2 * primeStr.length() + 16) > buf.limit()) {
break;
}
buf.asDoubleBuffer().put(0, (double) primeStr.length());
buf.position(buf.position() + 8);
buf.position(buf.position()
+ 2 * buf.asCharBuffer().put(primeStr).position());
buf.asLongBuffer().put(primes[primesWritten++]);
buf.position(buf.position() + 8);
}
buf.flip();
try {
file.write(buf);
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
buf.clear();
}
try {
System.out.println("File written is " + file.size() + " bytes.");
outputFile.close(); // Close the file and its channel
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
You should get the same output as for the previous example here.
How It Works
To start with, we just create a byte buffer with a capacity of 1024 bytes. All the view buffers are created
inside the inner while loop. Both loops end when primesWritten , which counts the number of
primes written to the file, reaches the length of the primes array. The inner loop loads up the buffer
and the outer loop writes the contents of the buffer to the file.
The first step in the inner loop is to create the prime string. This makes it possible to check whether
there is enough free space in the byte buffer to accommodate the string plus the two binary values - the
string length as type double and the prime itself of type long . If there isn't enough space, the break
statement will be executed so the inner loop will end, and the channel will write the buffer contents to
the file after flipping it. After the buffer has been written, the buffer's clear() method is called to reset
the position to 0 and the limit to the capacity.
When there is space in the byte buffer, the inner loop loads the buffer starting with the statement:
buf.asDoubleBuffer().put(0, (double)primeStr.length());
Search WWH ::




Custom Search