Random Access to Files

The examples we’ve seen so far have all read or written file content using streams. Streams provide sequential access to data and are particularly useful for network applications, which are often stream-oriented. Files stored on modern hard disks (as opposed to streaming tape drives) need not be accessed sequentially, and Java provides random access to files with the RandomAccessFile class. Example 3-8 demonstrates the use of random-access files by defining a list of strings stored in a file, along with an index to the position of each string. Note the use of writeInt( ) , writeLong( ), and writeUTF( ) to write integers, longs, and strings, and the use of readInt( ) , readLong( ), and readUTF( ) to read the corresponding values back. These methods are defined by the DataOutput and DataInput interfaces, which are also implemented by the DataOutputStream and DataInputStream classes. Note also the use of the seek( ) method to set the file position of a RandomAccessFile and the getFilePosition( ) method for querying the current position. Finally, don’t forget that, like streams, random-access files must be closed when they are no longer needed.

Example 3-8. WordList.java

package je3.io; import java.io.*; /** * This class represents a list of strings saved persistently to a file, * along with an index that allows random access to any string in the list. * The static method writeWords( ) creates such an indexed list in a file. * The class demostrates the ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.