-1

I have successfully created an object in a file using ObjectOutputStream but when i try to read that obj it gives an exception. Please help I am unable to handle this::java.io.EOFException

public class ObjInputObjOutput {
    public static void main(String[] args) {
        FileInputStream fs;
        ObjectInputStream os;
        try{
            fs=new FileInputStream("C:\\Users\\MYPC\\Desktop\\temp.txt");
            os=new ObjectInputStream(fs);
         os.readObject();
         Student s=(Student) os.readObject();
           s.toString();
        }catch(Exception e){System.out.println(e);}
    }
    }
    class Student implements Serializable
    {
    int rno;
    String add;
    float cgpa;
    String name;
    public Student(int rno, String add, float cgpa, String name) {
        this.rno = rno;
        this.add = add;
        this.cgpa = cgpa;
        this.name = name;
    }
    public String toString()
    {
        return "Roll no:"+rno+"\n"+"Add"+add+"\n"+"Cgpa"+cgpa+"\n"+"Name"+name;
    } 
}
user207421
  • 305,947
  • 44
  • 307
  • 483
coc champ
  • 69
  • 2
  • 9
  • Have you examined the saved file? Does it contain anything? Make sure it is not zero bytes. What is your code to save the student object? – Jamie Apr 30 '18 at 03:17
  • 1
    `ObjectOutputStream` creates a *binary* file, i.e. not a `.txt` file. – Andreas Apr 30 '18 at 03:18
  • yes its containing unreadable charecters – coc champ Apr 30 '18 at 03:19
  • You likely get `EOFException` because you're trying to read **two** objects from the file, and you probably only wrote one object when you created the file. --- Also, what is the point of `s.toString();`? It returns a string, so you'd probably want to print it or something. – Andreas Apr 30 '18 at 03:20
  • this is what my txt file contains ¬í ur [Lobjinputobjoutput.Student;ÿØTe¦!^  xp sr objinputobjoutput.Student'n+Uõˆk F cgpaI rnoL addt Ljava/lang/String;L nameq ~ xp@Hõà t my addt mynamesq ~ @„zá q ~ q ~ sq ~ @K… q ~ q ~ sq ~ @I™š q ~ q ~ – coc champ Apr 30 '18 at 03:22
  • Duplicate of [Having Trouble with ObjectInputStream/OutputStream](https://stackoverflow.com/q/21353846/207421https://stackoverflow.com/q/21353846/207421) – user207421 Apr 30 '18 at 07:53

1 Answers1

1

You are reading the object and throwing it away:

os.readObject();

and then trying to read another object that isn't there:

Student s=(Student) os.readObject();

and then converting that to a String and throwing it away:

   s.toString();

You only need the second of these three lines.

NB Serialized data is not text, and should not be stored in files with the ".txt" extension. You also should not use full pathnames. Your home directory won't be there on somebody else's computer.

user207421
  • 305,947
  • 44
  • 307
  • 483