Main Page

Previous Next

File Input and Output

The new file I/O capabilities introduced in Java 1.4 provide the potential for substantially improved performance at the cost of some slight increase in complexity over the I/O facilities of previous releases. There are three kinds of objects 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. We 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 we will be using FileInputStream objects for files that we 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. We will 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. We will see how to obtain a channel from a file stream object later in this chapter.

The way in which these types of object work together is illustrated in the diagram below:

Click To expand

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 the file that is encapsulated by the file stream. To read from a file, you call a method for the channel object to read data from the file into one or more buffers, and then retrieve the data from the buffers.

There are four classes defined in the java.io package that we will be using when we are working with files. As we have said, the FileInputStream and FileOutputStream classes define objects that provide access to a file for reading or writing respectively. You use an object of type RandomAccessFile when you want to access a file randomly, or when you want to use a single channel to both read from and write to a file. We will be exploring this, along with the FileInputStream class in the next chapter. You will see from the SDK documentation for the FileInputStream, FileOutputStream, and RandomAccessFile classes that they each provide methods for I/O operations. However, we will ignore these, as we will be using the services of a file channel to perform operations with objects of these stream classes. The only method from these classes that we will be using is the close() method, that closes the file and any associated channel.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor