O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required