Java Reference
In-Depth Information
In the try block, we first create a File object to represent the directory. If this directory does not
exist, the exists() method will return false and the mkdir() method for dir will be called to
create it. If the exists() method returns true , we must make sure that the File object represents a
directory, and not a file.
Having established the directory one way or another, we create a File object, aFile , to represent the
path to the file. We use this object to create a FileOutputStream object that will append data to the
file. Omitting the second argument to the FileOutputStream constructor or specifying it as false
would make the file stream overwrite any existing file contents. The file stream has to be created in a
try block because the constructor can throw a FileNotFoundException . Once we have a
FileOutputStream object, we call its getChannel() method to obtain a reference to the channel
that we will use to write the file.
The next step is to create a ByteBuffer object and load it up with the characters from the string. We create
a buffer with a capacity of 1024 bytes. This is so we can see clearly the difference between the capacity and
the limit after flipping. We could have created a buffer exactly the size required with the statement:
ByteBuffer buf = ByteBuffer.allocate(2*phrase.length());
You can see how the position, limit, and capacity values change from the output. We use the
putChar() method for the buffer object to transfer the characters one at a time in a loop and then
output the information about the buffer status again. The limit is still as it was but the position has
increased by the number of bytes written.
Finally, we write the contents of the buffer to the file. You can see here how flipping the buffer before
the operation sets up the limit and position ready for writing the data to the file.
The FileChannel object has a method, size() , which will return the length of the file in bytes as a
value of type, long . You could try this out by adding the following statement immediately after the
statement that writes the buffer to the channel:
System.out.println("The file contains " + outChannel.size() + " bytes.");
You should see that 48 bytes are written to the file each time, since phrase contains 24 characters. The
size() method returns the total number of bytes in the file so the number will grow by 48 each time
you run the program.
Using a View Buffer
The code in the previous example is not the only way of writing the string to the buffer. We could have
used a view buffer, like this:
ByteBuffer buf = ByteBuffer.allocate(1024);
CharBuffer charBuf = buf.asCharBuffer();
charBuf.put(phrase); // Transfer string to buffer
buf.limit(2*charBuf.position()); // Update byte buffer limit
// Create the file output stream channel
Search WWH ::




Custom Search