THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

The "random access" in the name of the class refers to the ability to set the read/write file pointer to any
position in the file and then perform operations. The additional methods in RandomAccessFile to support
this functionality are:


public longgetFilePointer()throws IOException

Returns the current location of the file pointer (in bytes) from the beginning
of the file.

public voidseek(long pos)throws IOException

Sets the file pointer to the specified number of bytes from the beginning of
the file. The next byte written or read will be the posth byte in the file, where
the initial byte is the 0th. If you position the file pointer beyond the end of the
file and write to the file, the file will grow.

public intskipBytes(int count)tHRows IOException

Attempts to advance the file pointer count bytes. Any bytes skipped over
can be read later after seek is used to reposition the file pointer. Returns the
actual number of bytes skipped. This method is guaranteed never to throw an
EOFException. If count is negative, no bytes are skipped.

public longlength()throws IOException

Returns the file length.

public voidsetLength(long newLength)tHRows IOException

Sets the length of the file to newLength. If the file is currently shorter, the
file is grown to the given length, filled in with any byte values the
implementation chooses. If the file is currently longer, the data beyond this
position is discarded. If the current position (as returned by
getFilePointer) is greater than newLength, the position is set to
newLength.

You can access the FileDescriptor for a RandomAccessFile by invoking its getFD method. You
can obtain a FileChannel for a RandomAccessFile by invoking its getChannel method.


Exercise 20.8: Write a program that reads a file with entries separated by lines starting with %% and creates a
table file with the starting position of each such entry. Then write a program that uses that table to print a
random entry (see the Math.random method described in "Math and StrictMath" on page 657).


20.7.3. The File Class


The File class (not to be confused with the file streams) provides several common manipulations that are
useful with file names. It provides methods to separate pathnames into subcomponents and to ask the file
system about the file a pathname refers to.


A File object actually represents a path, not necessarily an underlying file. For example, to find out whether
a pathname represents an existing file, you create a File object with the pathname and then invoke exists
on that object.

Free download pdf