11.1. File Read Operations

The process for reading a file parallels that of writing a file. You obtain a FileChannel object from a file stream, and use the channel to read data from the file into one or more buffers. Initially you will be using a channel object that you obtain from a FileInputStream object to read a file. Later you will be using a FileChannel object obtained from a RandomAccessFile object to read and write the same file. Like the FileOutputStream class, the FileInputStream class defines its own methods for file input, as does the RandomAccessFile class. However, I'll completely ignore these because the file channel methods for reading the file are much more efficient and will eventually supersede the stream methods. In any event, if you are curious to see how the old stream input mechanism works you can find details about the methods that read from a file stream in the descriptions for the FileInputStream and RandomAccessFile classes in the documentation that accompanies the JDK.

The starting point for reading a file is to create a FileInputStream object. Creating FileInputStream objects is not very different from creating FileOutputStream objects, so I'll explain how you do that first.

NOTE

In the examples in this chapter you'll be reading some of the files that you created in the last chapter, so I hope that you kept them.

11.1.1. Creating File Input Streams

A FileInputStream object encapsulates a file that is essentially intended to be read so the file must ...

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.