Question

I am having some issues at reading bytes from with readInt() when using RandomAccessFile whenever I want to print the File I get EOFException. The same error appears in the last catch Statement when I want to show the updated series of numbers. Here is my code:

import java.io.*;
import java.util.Scanner;
public class CentNumbers {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
int num;
RandomAccessFile numbers = new RandomAccessFile("Numbers.dat", "rw");

System.out.println("Saved numbers are:");
numbers.setLength(0);

for (int i = 0; i < 100; i++){
  num=(int)(Math.random()*100);
  numbers.writeInt(num);
  System.out.print(numbers.readInt()+" ");
  }
try{
do{
System.out.print("\nadd another number? (y/n):");

String x= input.next();

if (!x.equals("y")) throw new Exception("Comeback Soon");


    System.out.print("Write number :");
    int b=input.nextInt();
    numbers.seek(numbers.length());
    numbers.writeInt(b);

 } while(true);

}//end try


catch ( Exception e){

    System.out.println("Saved numbers are:");

    for (int i=0; i<numbers.length();i++){
        numbers.seek(i*4);
        System.out.print(numbers.readInt()+" ");

    }//end for
    System.out.println();
    System.out.println(e.getMessage() );
    numbers.close();

    }//end catch

 }
}
Was it helpful?

Solution

In this loop, you are attempting to read from the end of the file (your readInt() comes after the writeInt(), without resetting the position).

for (int i = 0; i < 100; i++){
  num=(int)(Math.random()*100);
  numbers.writeInt(num);
  System.out.print(numbers.readInt()+" ");
}

In this loop, the number of numbers in the file is not equal to the length of the file in bytes, because there are 4 bytes per int, therefore you are reading past the end of the file.

for (int i=0; i<numbers.length();i++){
    numbers.seek(i*4);
    System.out.print(numbers.readInt()+" ");

}//end for

note for the future: when dealing with issues like this, stepping through the code in a debugger is a good way to figure out where your logic problems are. you could look at the RAF position and length after each step and you should be able to figure out what you are doing wrong.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top