Java Reference
In-Depth Information
Display 10.20
File I/O of an Array Object (part 3 of 3)
Sample Dialogue
Array written to file arrayfile.
Now let's reopen the file and display the array.
The following array elements were read from the file:
Number = 1 Letter = A
Number = 2 Letter = B
End of program.
10.5
Random Access to Binary Files
Any time, any where.
Common response to a challenge for a confrontation
The streams for sequential access to files, which we discussed in the previous sections
of this chapter, are the ones most often used for file access in Java. However, some
applications that require very rapid access to records in very large databases require
some sort of random access to particular parts of a file. Such applications might best
be done with specialized database software. But perhaps you are given the job of writ-
ing such a package in Java, or perhaps you are just curious about how such things are
done in Java. Java does provide for random access to files so that your program can
both read from and write to random locations in a file. In this section we will describe
simple uses of random access to files.
Reading and Writing to the Same File
If you want random access to both read and write to a file in Java, you use the stream
class RandomAccessFile , which is in the java.io package like all other file I/O classes.
A random access file consists of a sequence of numbered bytes. There is a kind of
marker called the file pointer that is always positioned at one of these bytes. All reads
and writes take place starting at the location of the file pointer. You can move the file
pointer to a new location with the method seek .
Although a random access file is byte oriented, there are methods to allow for reading or
writing values of the primitive types and of string values to a random access file. In fact,
these are the same methods as those we already used for sequential access files, as previously
discussed. A RandomAccessFile stream has methods writeInt , writeDouble , writeUTF ,
and so forth as well as methods readInt , readDouble , readUTF , and so forth. However, the
class RandomAccessFile does not have the methods writeObject or readObject . The most
important methods of the class RandomAccessFile are given in Display 10.21. A demon-
stration program for random access files is given in Display 10.22.
file pointer
 
Search WWH ::




Custom Search