1

我在运行应用程序文件尝试将对象写入 .dat 文件时收到 NotSerializableException。

    try{
        Person[] personList = new Person[3];
        personList[0] = new TeamLeader(8, "Mike Johnson", 29);
        personList[1] = new Engineer(0.4,"Russell Sanders", 22);
        personList[2] = new Engineer(0.7, "Steven Peterson", 25);
        out = new ObjectOutputStream(new FileOutputStream("persons.dat"));
        for(int i = 0; i < personList.length; i++) {
            out.writeObject(personList[i]);//error line 85
        }
        //out.writeObject(personList);
    }

    catch(IOException e) {
        System.out.println("Problem writing file");
        e.printStackTrace();
    } 

错误

java.io.NotSerializableException: TeamLeader
     at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java: 346)
     at CharlieBrownP6.main(CharlieBrownP6.java: 85)

错误继续关于写入因相同错误而中止

4

1 回答 1

2

调用 writeObject 的对象必须实现Serializable接口(参考)。

于 2013-04-13T04:49:57.523 回答