Java Reference
In-Depth Information
The above example does not adequately demonstrate the direct access capabilities
of a RandomAccessFile object, since we have processed the whole of the fi le from
start to fi nish, dealing with records in the order in which they are stored on the fi le.
We should also be able to retrieve individual records from anywhere in the fi le and/
or make modifi cations to those records. The next example shows how this can be
done for our accounts fi le.
Example
//Allows the user to retrieve individual account
//records and modify their balances.
import java.io.*;
import java.util.*;
public class RanFile2
{
private static fi nal int REC_SIZE=48;
private static fi nal int SURNAME_SIZE=15;
private static fi nal int NUM_INITS=3;
private static long acctNum=0;
private static String surname, initials;
private static fl oat balance;
public static void main(String[] args)
throws IOException
{
Scanner input = new Scanner(System.in);
RandomAccessFile ranAccts =
new RandomAccessFile("accounts.dat", "rw");
long numRecords = ranAccts.length()/REC_SIZE;
String reply;
long currentPos; //File pointer position.
do
{
System.out.print("\nEnter account number: ");
acctNum = input.nextLong();
while ((acctNum<1) || (acctNum>numRecords))
{
System.out.println(
"\n*** Invalid number! ***\n");
System.out.print(
"\nEnter account number: ");
acctNum = input.nextLong();
}
Search WWH ::




Custom Search