-2

我得到以下信息:

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)

下面是我试图运行的代码:

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();
        }
    }
4

1 回答 1

2

当你这样做时,FileWriter fw = new FileWriter(doggy);它以写入模式打开文件并删除文件的先前数据。这就是为什么阅读它提供的文件的原因,EOFException因为文件中没有什么可读取的。

如果您这样做, FileWriter fw = new FileWriter(doggy,true);则不会出现错误,因为它不会删除文件的先前数据。

于 2014-01-15T06:58:32.657 回答