Java Reference
In-Depth Information
When run, Program P7.5 produces the following output:
Part number: 4250
Price: $12.95
Part number: 3000
Price: $17.50
Part number: 6699
Price: $49.99
Part number: 2270
Price: $19.25
After the file has been created, we can read the next
Part
record with this:
public static Part readPartFromFile(DataInputStream in) throws IOException {
return new Part(in.readInt(), in.readDouble());
} //end readPartFromFile
This assumes the following declaration:
DataInputStream in = new DataInputStream(new FileInputStream("parts.bin"));
7.7 Random Access Files
In the normal mode of operation, data items are read from a file in the order in which they are stored. When a file is
opened, one can think of an imaginary pointer positioned at the beginning of the file. As items are read from the file,
this pointer moves along by the number of bytes read. At any time, this pointer indicates where the next read (or write)
operation would occur.
Normally, this pointer is moved implicitly by a read or write operation. However, Java provides facilities for
moving the pointer explicitly to any position in the file. This is useful if we want to be able to read the data in random
order, as opposed to sequential order.
For example, consider the parts binary file created earlier. Each record is 12 bytes long. If the first record starts at
byte 0, then the
n
th
record would start at byte 12(
n
- 1). Suppose we want to read the 10
th
record without having to read
the first nine. We work out that the 10
th
record starts at byte 108. If we can position the file pointer at byte 108, we can
then read the 10
th
record.
In Java, the
RandomAccessFile
class provides methods for working with random access files. The following
statement declares that
parts.bin
will be treated as a random access file;
rw
is the file mode, and it means “read/
write”—we will be allowed to read from the file
and
write to it.
RandomAccessFile fp = new RandomAccessFile("parts.bin", "rw");
If we want to open the file in read-only mode, we use
r
instead of
rw
.
Initially, the file pointer is 0, meaning it is positioned at byte 0.
As we read data from or write data to the file, the pointer value changes. In the parts example, after we read (or
write) the first record, the pointer value would be 12. After we read (or write) the 5
th
record, the value would be 60.
Note, though, that the 5
th
record starts at byte 48.
Search WWH ::
Custom Search