Java Reference
In-Depth Information
file.close(); // Close the output stream & the channel
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
If you run this a couple of times and look into the byteData.txt file with your plain text editor, you
should find:
Garbage in, garbage out
Garbage in, garbage out
There are no gaps between the letters this time because the Unicode character were converted to bytes
in the default character encoding on your system by the getBytes() method for the string.
How It Works
We create the file stream and the channel essentially as in the previous example. This time the buffer is
created with the precise amount of space we need. Since we will be writing each character as a single
byte, the buffer capacity only needs to be the length of the string, phrase .
We convert the string to a byte array in the local character encoding using the getBytes() method
defined in the String class. We transfer the contents of the array to the buffer using the relative put()
method for the channel. After a quick flip of the buffer, we use the channel's write() method to write
the buffer's contents to the file.
We could have written the conversion of the string to an array plus the sequence of operations with the
buffer and the channel write operation much more economically, if less clearly, like this:
outChannel.write(buf.put(myStr.getBytes()).flip());
This makes use of the fact that the buffer methods we are using here return a reference to the buffer so
we can chain them together.
Writing Varying Length Strings to a File
So far, the strings we have written to the file have all been of the same length. It is very often the case
that you will want to write a series of strings of different lengths to a file. In this case, if you want to
recover the strings from the file, you need to provide some information in the file that allows the
beginning and/or end of each string to be determined. One possibility is to write the length of each
string to the file immediately preceding the string itself.
To do this, we can get two view buffers from the byte buffer we will use to write the file, one of type
IntBuffer and the other of type CharBuffer . Let's see how we can use that in another example that
writes strings of various lengths to a file.
Search WWH ::




Custom Search