10.2. File Input and Output

The new file I/O capabilities that were introduced in Java 1.4 provided the potential for substantially improved performance over the I/O facilities of previous releases, the only cost being some slight increase in complexity. Three kinds of objects are involved in reading and writing files using the new I/O capability:

  • A file stream object that encapsulates the physical file that you are working with. You saw how to create FileOutputStream objects at the end of the previous chapter, and you use these for files to which you want to write. In the next chapter, you will be using FileInputStream objects for files that you want to read.

  • One or more buffer objects in which you put the data to be written to a file, or from which you get the data that has been read. You'll learn about buffer objects in the next section.

  • A channel object that provides the connection to the file and does the reading or writing of the data using one or more buffer objects. You'll see how to obtain a channel from a file stream object later in this chapter.

The way in which these types of objects work together is illustrated in Figure 10-1.

Figure 10.1. Figure 10-1

The process for writing and reading files is basically quite simple. To write to a file, you load data into one or more buffers that you have created and then call a method for the channel object to write the data to ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.