Recipe 10.16 Seeking


You need to read from or write to a particular location in a file, such as an indexed file.


Use a RandomAccessFile.


The class allows you to move the read or write position when writing to any location within a file or past the end. This allows you to create or access "files with holes" on some platforms and lets you read or write indexed or other database-like files in Java. The primary methods of interest are void seek(long where), which moves the position 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 position.

RandomAccessFile class also implements the DataInput and DataOutput interfaces, so everything I said about DataStreams in Recipe 10.15 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:

import*; /**  * Read a file containing an offset, and a String at that offset.  */ public class ReadRandom {     final static String FILENAME = "random.dat";     protected String fileName;     protected RandomAccessFile seeker;     public static void main(String argv[]) throws IOException {         ReadRandom r = new ReadRandom(FILENAME);         System.out.println("Offset is " + r.readOffset( ));         System.out.println("Message is \"" + r.readMessage( ) + "\".");     }     /** Constructor: save filename, construct RandomAccessFile */     public ReadRandom(String fname) throws IOException {         fileName = fname;         seeker = new RandomAccessFile(fname, "r");     }     /** Read the Offset field, defined to be at location 0 in the file. */     public int readOffset( ) throws IOException {;         return seeker.readInt( );     }     /** read the message at the given offset */     public String readMessage( ) throws IOException { ));    // move to the offset         return seeker.readLine( );        // and read the String     } }

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: