Java Reference
In-Depth Information
Byte buffer after limit update:
position = 0 Limit = 132 length = 132
Buffer contents written to file.
You can inspect the contents of the file with a plain text editor. Remember that the data is written as
Unicode characters.
How It Works
You first create an array of three strings that are written to the file. You can add more to the array if you
like. I kept it at three to keep the volume of output down. You've seen the first part of the code that sets
up the path and channel before, so I'm going straight to where the buffer is loaded.
You set up the byte buffer and a view buffer holding characters with the statements:
ByteBuffer buf = ByteBuffer.allocate(1024);
CharBuffer charBuf = buf.asCharBuffer();
After outputting the state of the view buffer
charBuf
, you create the
Formatter
object that you use to
load the buffer:
Formatter formatter = new Formatter(charBuf);
The
format()
method for this
Formatter
object writes data to
charBuf
.
After defining the
number
variable that stores the proverb sequence number, you load the buffer and write
to the file in a
for
loop like this:
for(String phrase : phrases) {
// Load the buffer...
// Write the buffer to the file...
}
This loop iterates over each of the strings in the
phrases
array. You load a proverb from
phrases
into
the view buffer with the statement:
formatter.format("Proverb%2d: %s%s", ++number, phrase,
separator);
This transfers the incremented value of
number
followed by the string,
phrase
, and a separator character
formatted according to the first argument to the
format()
method. The separator character is useful in
separating records when the file is read. Executing this statement updates the position for the view buffer,
but not the byte buffer.
You flip the view buffer with the statement:
charBuf.flip(); // Flip the view buffer
Flipping the view buffer sets its limit as the current position and resets its position to 0. The
length()
method for the view buffer returns the number of characters in the buffer, which is
limit-position
.
You could obtain the same result by calling the
remaining()
method that the
CharBuffer
class inherits
from the
Buffer
class. You update the limit for the byte buffer with this statement: