I am getting following:

java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at com.Temp.main(Temp.java:62)

Below is the code that I am trying to run:

class Dog implements Serializable {
    private static final long serialVersionUID = 1L;
    int age = 0;
    String color = "Black";
}

public class Temp {
    public static void main(String[] args) {
        FileOutputStream fos;
        ObjectOutputStream oos;
        FileInputStream fis;
        ObjectInputStream ios;
        File doggy;
        try {
            Dog fluffy = new Dog();
            fos = new FileOutputStream("DOG_store.txt");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(fluffy);
            fos.close();
            oos.close();

            doggy = new File("DOG_store.txt");
            FileWriter fw = new FileWriter(doggy); // **This is Causing ISSUE**

            fis = new FileInputStream("DOG_store.txt");
            ios = new ObjectInputStream(fis);
            Dog scrappy = (Dog) ios.readObject();
            fis.close();
            ios.close();
            System.out.println(scrappy.age + " " + scrappy.color);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (ClassNotFoundException cfne) {
            cfne.printStackTrace();
        }
    }
有帮助吗?

解决方案

when you do FileWriter fw = new FileWriter(doggy); it opens file in write mode and deletes the previous data of file. Thats why whie reading the file it gives EOFException because there is nothing to read in file.

If you do like this FileWriter fw = new FileWriter(doggy,true); then there will be no error because it does not delete the previous data of file.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top