I have an assignment to write some numbers in a text file using PrintStream and then reading from that same file using RandomAccessFile. While the writing part works as intended, I get the following output when running my code.
807416096
840971040
874525984
Exception in thread "main" java.io.EOFException
908080928
941635872
at java.io.RandomAccessFile.readInt(RandomAccessFile.java:776)
at Problema4.main(Problema4.java:21)
Java Result: 1
Here is the code:
import java.io.*;
import java.util.*;
public class Problema4 {
public static void main(String[] args) throws IOException, FileNotFoundException
{
PrintStream ps = new PrintStream(new FileOutputStream("fisiernou.txt"));
int i=0;
while (i<11)
{
ps.print(i);
ps.print(" ");
i++;
}
ps.close();
RandomAccessFile raf = new RandomAccessFile("fisiernou.txt", "r");
raf.seek(0);
//System.out.println(raf.readInt());
while (raf.getFilePointer()<raf.length())
System.out.println(raf.readInt());
raf.close();
}
}
You are writing integer as strings ( ps.print(i) ). If you write 1, in the file you are writting the ascii character of 1. Suposse this is the unique number we write, the file then have only one byte.
When reading, you are using raf.readInt(). This method reads 4 bytes and convert them to an integer. If now you try to read your file, this only contains one byte (the ascii character of 1), and then you get an EOF excepcion.
Use the same type of method for writting and reading. You can write with FileOutputStream.write(int).