WHAT YOU'LL LEARN IN THIS CHAPTER
• How to obtain a file channel for reading a file
• How to use buffers in file channel read operations
• How to read different types of data from a file
• How to retrieve data from random positions in a file
• How you can read from and write to the same file
• How you can do direct data transfer between channels
• What a memory-mapped file is and how you can access a memory-mapped file
• What a file lock is and how you can lock all or part of a file
In this chapter you investigate how you read files containing basic types of data. You explore how to read
files sequentially or at random and how you can open a file for both read and write operations.
FILE READ OPERATIONS
The process for reading a file parallels that of writing a file so if you are comfortable with writing files,
this chapter is going to be easy. You have three ways for reading files, all provided by static methods in the
• The newInputStream() method returns an InputStream object, which you can use to read a binary
• The newBufferedReader() method returns a BufferedReader object, which you can use to read
a file containing character data.
• The newByteChannel() method that you used in the Chapter 10 returns a reference to a FileChan-
nel object as type SeekableByteChannel , which you can use to read a file when the READ open
option is in effect. You can read binary or character data from the file.
I cover the first two briefly because they are quite simple and then concentrate on the third option, which
uses a FileChannel object.
Reading a File Using an Input Stream
Here's how you create an input stream to read a given file from the beginning: