Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Seeking

Problem

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

Solution

Use a RandomAccessFile.

Discussion

The class java.io.RandomAccessFile allows you to move the read/write position to any location within a file, or past the end when writing. This allows you to create or access “files with holes” on some platforms and lets you read/write indexed or other database-like files in Java. The primary methods of interest are void(long where), which moves the position for the next read/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 Section 9.14 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 java.io.*; /** * 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata