Java Reference
In-Depth Information
buf.flip(); // Flip the buffer ready for file write
System.out.println("Buffer after flip: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tcapacity = "
+ buf.capacity());
// Write the file
try {
outChannel.write(buf); // Write the buffer to the file channel
outputFile.close(); // Close the output stream & the channel
System.out.println("Buffer contents written to file.");
} catch (IOException e) {
e.printStackTrace(System.err);
}
System.exit(0);
}
}
There is some command-line output from the program to trace what is going on. After you have
compiled and run this program, you should see the output:
File stream created successfully.
New buffer: position = 0 Limit = 1024 capacity = 1024
Buffer after loading: position = 48 Limit = 1024 capacity = 1024
Buffer after flip: position = 0 Limit = 48 capacity = 1024
Buffer contents written to file.
You can inspect the contents of the file, charData.txt , using a plain text editor. They will look
something like the following.
G a r b a g e i n , g a r b a g e o u t
There are spaces between the characters, because we are writing Unicode characters to the file, and two bytes
are written for each character in the original string. Your text editor may represent the first of each byte pair
as something other than spaces, or possibly not at all, as they are bytes that contain zero. You might even find
that your plain text editor will only display the first ' G '. If so, try to find another editor. If you run the
example several times, the phrase will be appended to the file for each execution of the program.
Don't be too hasty deleting this or other files we will write later in this chapter, as we
will reuse some of them in the next chapter when we start exploring how to read files.
How It Works
We have defined three String objects:
phrase - The string that we will write to the file
dirname - The name of the directory we will create
filename - The name of the file
Search WWH ::




Custom Search