Reading from random access file in Java

user3003064 picture user3003064 · Oct 26, 2014 · Viewed 9.9k times · Source

I am trying to set up a while loop that will read from a RandomAccessFile and stop when it reaches the end of the file. But every time I try running the program I get an error.

RandomAccessFile raf = new RandomAccessFile(filename, "rw");
    final int EOF = -1;

    while(raf.readInt() != EOF){

    id = raf.readInt();
    existingMileage = raf.readInt();
    gasCost = raf.readInt();
    ndays = raf.readInt();
    rate = raf.readInt();
    totalCharge = raf.readInt();
    discount = raf.readInt();
    tax = raf.readInt();
    netCharge = raf.readInt();
    returnMileage = raf.readInt();

    }

This is the error I am getting:

Exception in thread "main" java.io.EOFException
at java.io.RandomAccessFile.readInt(Unknown Source)
at TakeHome.TakeHome.fileReaderMethod(TakeHome.java:127)
at TakeHome.TakeHome.main(TakeHome.java:20)

Answer

user207421 picture user207421 · Oct 26, 2014
 final int EOF = -1;

You made that up. It isn't in the Javadoc. The readInt() method doesn't return -1 at end of file. It can't. -1 is an in-band value. It throws the very EOFException you are getting.

You're also throwing the int that you read at the EOF test away, so you're reaching end of file sooner than you should be.

You should loop while (true), catch EOFException, and break when you catch it.