Java Reference
In-Depth Information
All of the
put()
methods for the byte buffers we are using here automatically update the buffer
position, so we can flip each buffer as soon as the data is loaded. An alternative to allocating this byte
buffer directly to accommodate the byte array from the string, is to call the static
wrap()
method in the
ByteBuffer
class that wraps a byte array. We could achieve the same as the previous two statements
with the single statement:
buffers[1] = ByteBuffer.wrap(primeStr.getBytes());
Since the
wrap()
method creates a buffer with a capacity the same as the length of the array, and with
the position set to zero and the limit to the capacity, we don't need to flip the buffer - it is already in a
state to be written.
The three buffers are ready so we write the array of buffers to the file like this:
try {
file.write(buffers);
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
Finally, we ready the first and third buffers for the next iteration by calling the
clear()
method for
each of them:
buffers[0].clear();
buffers[2].clear();
Of course, the second buffer is recreated on each iteration, so there is no need to clear it. Surprisingly
easy wasn't it?
Summary
In this chapter, we have discussed the facilities for checking out physical files and directories, and
writing basic types of data to a file. The important points we have discussed include:
An object of the class
File
can represent the path to a physical file.
❑
An object of type
FileDescriptor
can also represent a physical file.
❑
A
FileOutputStream
object can be created from a
File
object and the file will be opened
for writing. If the file does not exist it will be created where possible.
❑
A
FileChannel
object for a file is returned by the
getChannel()
method for a file
stream object.
❑
A buffer contains data to be written to a file, or data that has been read from a file. Only
ByteBuffer
objects can be used directly in file I/O operations.
❑
A buffer's position is the index position of the first element in the buffer to be written or read.
A buffer's limit specifies the index position of the first element that is
not
to be written or read.
❑