Java Reference
In-Depth Information
Reading Files
In this chapter we will investigate how we can read files containing basic types of data. We will be
exploring how to read files sequentially or at random, and how we can open a file for both read and
write operations.
In this chapter you will learn:
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 and write 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.
File Read Operations
The process for reading a file parallels that of writing a file. You obtain a FileChannel object from a file
from a file stream, and use the channel to read data from the file into one or more buffers. Initially we will be
using a channel object from a FileInputStream object to read a file. Later when we want to read and
write the same file we will be using a FileChannel object obtained from a RandomAccessFile object.
Like the FileOutputStream class, the FileInputStream class defines its own methods for file input, as
does the RandomAccessFile class. However, we will completely ignore these because the file channel
methods for reading the file are much more efficient and will eventually obsolete the stream methods. In any
event, if you are curious to see how the old stream input mechanism works you can find details of the
methods that read from a file stream in the descriptions for the FileInputStream and
RandomAccessFile classes in the documentation that accompanies the SDK.
Search WWH ::




Custom Search