Java Reference
In-Depth Information
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
When you execute this it should produce the rather terse output:
Proverbs written to file.
You can check the veracity of this assertion by inspecting the contents of the file with a plain text editor.
How It Works
The program writes the strings from the array, sayings , to the file.
We create a String array, sayings[] , that contains seven proverbs that are written to the stream in
the for loop. We put the length of each proverb in the buffer using the putInt() method for the
ByteBuffer object. We then use a view buffer of type CharBuffer to transfer the string to the
buffer. The contents of the view buffer will start at the current position for the byte buffer. This
corresponds to the byte immediately following the string length.
Transferring the string into the view buffer only causes the view buffer's position to be updated. The
byte buffer's position is still pointing back at the byte following the string length where the first
character of the string was written. We 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 will be created. You can then look at the
contents. If you run the program again, the same proverbs will be appended to the file, so there will be
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 will be added at the end of the existing file.
After writing the contents of the byte buffer to the file, we 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.
As we will write a program to read the proverbs.txt file back in the next chapter, you should leave
it on your disk.
Direct and Indirect Buffers
When you allocate a byte buffer by calling the allocate() method for the ByteBuffer class, you
get an indirect buffer . An indirect buffer is not used by the native I/O operations. Data to be written to
a file has to be copied to an intermediate buffer in memory before the write operation can take place.
Similarly, after a read operation the data is copied from the input buffer used by your operating system
to the indirect buffer that you allocate.
Search WWH ::




Custom Search