Java Reference
In-Depth Information
Writing Files
In this chapter, we will be looking at ways in which basic data can be written to a file using the new file
I/O capability. The JDK 1.4 release introduced this new mechanism for file I/O that supersedes the
read/write capability provided by readers and writers from the java.io package when applied to file
streams. Since the new file I/O does everything that the old capability does, and does it better, we will
focus just on that.
In this chapter you will learn:
The principles of reading and writing files using the new I/O.
How to obtain a file channel for a file.
How to create a buffer and load it with data.
What view buffers are and how you use them.
How you use a channel object to write the contents of a buffer to a file.
File I/O Basics
If you are new to programming file operations, there are a couple of things that may not be apparent to
you and can be a source of confusion so let's clarify them before we go any further.
Firstly, let's consider the nature of a file. Once you have written data to a file, you can regard it as just a
linear sequence of bytes. The bytes in a file are referenced by their offset from the beginning, so the first
byte is byte 0, the next byte is byte 1, the third byte is byte 2, and so on through to the end of the file. If
there are n bytes in a file the last byte will be at offset n-1 . There is no specific information in the file
about how the data originated or what it represents unless you explicitly put it there. Even if there is,
you need to know that it's there and read and interpret the data accordingly.
Search WWH ::




Custom Search