Java Reference
In-Depth Information
Transferring the string into the view buffer causes only the view buffer's position to be updated. The byte
buffer's position is still pointing at the byte following the binary string length value where the first char-
acter of the string was written. You therefore have to increment the position for the byte buffer by twice
the number of characters in the string before flipping it to make it ready to be written to the file.
The first time you run the program, the file doesn't exist, so it is created. You can then look at the con-
tents. If you run the program again, the same proverbs are appended to the file, so there is a second
set. Alternatively, you could modify the sayings[] array to contain different proverbs the second time
around. Each time the program runs, the data is added at the end of the existing file.
After writing the contents of the byte buffer to the file, you call its clear() method to reset the position
to zero and the limit back to the capacity. This makes it ready for transferring the data for the next proverb
on the next iteration. Remember that it doesn't change the contents of the buffer, though.
Using a Formatter Object to Load a Buffer
You saw the java.util.Formatter class when I introduced the printf() method that you can use with the
System.out stream object in Chapter 8. The Formatter class defines a constructor that accepts a reference
of type java.lang.Appendable as an argument, and because the PrintStream and PrintWriter classes
implement the Appendable interface, you can construct a Formatter object that formats data into these
objects. The CharBuffer class also implements the Appendable interface so you can create a Formatter
object that formats data into a view buffer of type CharBuffer . Here's how you might create a Formatter
object ready for use with a view buffer:
ByteBuffer buf = ByteBuffer.allocate(1024); // Byte buffer
CharBuffer charBuf = buf.asCharBuffer(); // View buffer
Formatter formatter = new Formatter(charBuf); // Formatter to write view buffer
You can now use the format() method for the Formatter object to format data values into the view
buffer charBuf . Recall that the format() method works just like printf() — with the first argument being
a format string and the arguments that follow specifying the data values to be formatted. Of course, writing
data into the view buffer leaves the backing byte buffer's limit unchanged, so you must update this to reflect
the data that is now in the buffer before attempting to write the buffer's contents to the channel. You can see
how this works with a simple example.
TRY IT OUT: Using a Formatter Object to Load a Buffer
Here's the code to use a Formatter object to prepare the data to be written to a file:
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
// Files and Path
import java.nio.channels.WritableByteChannel;
import java.nio.*;
// ByteBuffer and
CharBuffer
Search WWH ::




Custom Search