O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required