// File: ReadDesiredInteger.java // Test the RandomFileAccess class by allowing the user to specify the // integer to read by its position in the file // Note updated ReadInt() routine import java.io.*; import java.util.*; public class ReadDesiredInteger { static int ReadInt(DataInputStream Input) throws java.io.IOException {return(Integer.valueOf(Input.readLine()).intValue()); } public static void main(String[] args) throws java.io.IOException {int Value,Position; // Associate the disk file with the File object File BinaryInputFile=new File("int.bin"); // Now, open a stream from the input file RandomAccessFile BinaryDataInput= new RandomAccessFile(BinaryInputFile,"r"); DataInputStream KBD=new DataInputStream(System.in); int intsInBinaryFile=(int)BinaryInputFile.length()/4; // File Length in int System.out.println("Enter Integer in Range 0 to "+((int)intsInBinaryFile-1)); System.out.print("Signifying the Integer to Read from"+ " File. Negative # Quits >"); System.out.flush(); Position=ReadInt(KBD); while (Position>=0) { BinaryDataInput.seek(Position*4); try { System.out.println("Read "+BinaryDataInput.readInt()); } catch (java.io.IOException EOF) System.out.println("Position "+Position+" is Out of Range"); System.out.println("Enter Integer in Range 0 to "+((int)intsInBinaryFile-1)); System.out.print("Signifying the Integer to Read from"+ " File. Negative # Quits >"); System.out.flush(); Position=ReadInt(KBD); } } }