Question

I have a class that reads the written output of a Student[] array object

here is the code

import java.io.*;

// I use this class to read the final ouput "students_updated.dat"
public class StudentArrayObjectFileReader {

public static void main(String[] args) {
    try {
        ObjectInputStream fileReader = new ObjectInputStream(new FileInputStream("students_updated.dat"));
        Student[] studs = (Student[]) fileReader.readObject();
        fileReader.close();

        // List the records in console
        for (int i = 0; i < studs.length; i++) {
            System.out.printf("%7d %-35s %-5s %1d %-6s%n",studs[i].getID(), studs[i].getName(), studs[i].getCourse(), studs[i].getYr(), studs[i].getGender());
        }
    } catch (FileNotFoundException fnfe) {

        fnfe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
 }
}

problem is that it has an error when reading the Student[] studs = (Student[]) fileReader.readObject();

as stated here

java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2571)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at StudentArrayObjectFileReader.main(StudentArrayObjectFileReader.java:9)

any idea on what could be the problem? Thanks in advance..

this is how the students_updated.dat was written

    public void saveStudentArray() { // studs print to student_updated.dat
    try{
        output.writeObject(studs); // write the final studs
        output.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}

with its ObjectInputStream declared in the constructor of where this method is

Was it helpful?

Solution

Check the contents of the students_updated.dat file. readObject() function expects the file to contain a serialized object.

Does the file contain a serialized object? Check if the serialization succeeded without anything going wrong?

If you're trying to construct the array from a plain text file, you should not use readObject().

Visit this link for a sample of how to serialize and deserialize an array - Can I serialize an array directly...

OTHER TIPS

Move this line:

fileReader.close();

after your for loop.

In Java, the creation of a variable is simply creating a reference to some location in memory. The act of casting the object read from fileReader into your array of students just creates a pointer to the correct place in memory. If you then remove that place by closing the fileReader, you remove the location studs is pointing to.

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