import java.io.*;
public class ReadRandom
{
public static String readLine() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
public static int getRecordNumber() throws IOException, NumberFormatException
{
System.out.println( "Record number (-1 to quit)? ");
return Integer.parseInt(readLine());
}
public static void main(String[] args)
{
int dataSize; // Number of elements in File
int rn; // Record number
double value; // Value of requested record
int sizeOfInt = 4; // size of int variable
int sizeOfDouble = 8; // size of double variable
boolean wantsToQuit = false;
try
{
File fi = new File( "Data.bin ");
RandomAccessFile rin = new RandomAccessFile(fi, "r ");
dataSize = rin.readInt();
System.out.println( "\nFile has " + dataSize + " elements\n ");
while (!wantsToQuit)
{
rn = getRecordNumber();
wantsToQuit = (rn == -1);
if (!wantsToQuit)
{
rin.seek(sizeOfInt + rn * sizeOfDouble); // MARK!!!!!!!!!!!!!
value = rin.readDouble();
System.out.println( "record " + rn + " = " + value);
}
}
}
catch (IOException e)
{
System.err.println(e);
System.out.println(e.getMessage());
e.printStackTrace();