Reputation:
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)
Upvotes: 1
Views: 13463
Reputation: 31
This is one way to handle a RandomAccessFile:
RandomAccessFile file = new RandomAccessFile("testFile", "r");
//random code in between
while(true){
try{
//do stuff with code, like reading from file
} catch(EOFException e){
break;
}
}
//do some more stuff if you like
file.close();
Upvotes: 2
Reputation: 310911
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.
Upvotes: 4
Reputation: 51
The file you are reading needs to be also created as a binary file.
If you are trying to read from a file that you created as text then the reader will read 4 bytes for the int and for example if you have a sequence of numbers 12345678 the reader doesn't know that these are separate numbers and will treat it as one integer and then go to the end of file.
Another thing to mention is that you need to catch the EOFException
to end the loop cause -1 can also be an integer.
Hope that helps.
EDIT: Try this
RandomAccessFile raf = new RandomAccessFile(new File("/path/to/file"), "rw");
int numberCounter = 0;
int totalNumbers = 10;
for (int i = 0; i < totalNumbers; i++)
{
raf.writeInt(i * 2);
}
raf.seek(0);
try
{
while (true)
{
int id = raf.readInt();
System.out.println(id);
numberCounter++;
}
}
catch (EOFException ex)
{
System.out.println("Total number " + numberCounter);
System.out.println("End of file reached!");
}
finally
{
raf.close();
}
Output:
0
2
4
6
8
10
12
14
16
18
Total number 10
End of file reached!
Upvotes: -1