Java Reference
In-Depth Information
sition for the next read or write to where ; int skipBytes(int howmany) , which moves the
position forward by howmany bytes; and long getFilePointer() , which returns the posi-
tion.
The RandomAccessFile class also implements the DataInput and DataOutput interfaces,
so everything I said about DataStreams in Reading/Writing Binary Data also applies here.
This example reads a binary integer from the beginning of the file, treats that as the position
to read from, finds that position, and reads a string from that location within the file:
public
public class
class ReadRandom
ReadRandom {
final
final static
static String FILENAME = "random.dat" ;
protected
protected String fileName ;
protected
protected RandomAccessFile seeker ;
public
public static
static void
void main ( String [] argv ) throws
throws IOException {
ReadRandom r = new
new ReadRandom ( FILENAME );
System . out . println ( "Offset is " + r . readOffset ());
System . out . println ( "Message is \"" + r . readMessage () + "\"." );
}
/** Constructor: save filename, construct RandomAccessFile */
public
public ReadRandom ( String fname ) throws
throws IOException {
fileName = fname ;
seeker = new
new RandomAccessFile ( fname , "r" );
}
/** Read the Offset field, defined to be at location 0 in the file. */
public
public int
int readOffset () throws
throws IOException {
seeker . seek ( 0 );
// move to very beginning
return
return seeker . readInt ();
// and read the offset
}
/** Read the message at the given offset */
public
public String readMessage () throws
throws IOException {
seeker . seek ( readOffset ());
// move to the offset
return
return seeker . readLine ();
// and read the String
}
}
Search WWH ::




Custom Search