【发布时间】:2015-08-04 14:37:38
【问题描述】:
很抱歉,如果这已经被问到了,但是我在序列化我制作的类时遇到了一些问题。我已经测试过字符串和数组列表,但是当我尝试使用 NoteCard(一个由两个字符串组成的类)时,在序列化和反序列化时出现错误。这些是我在运行程序时遇到的错误。
java.io.NotSerializableException: com.leopoldmarx.note.notecard.NoteCard
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.leopoldmarx.note.program.Driver.main(Driver.java:22)
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: com.leopoldmarx.note.notecard.NoteCard
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.leopoldmarx.note.program.Driver.main(Driver.java:33)
Caused by: java.io.NotSerializableException: com.leopoldmarx.note.notecard.NoteCard
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.leopoldmarx.note.program.Driver.main(Driver.java:22)
错误代码如下:
NoteCard test = new NoteCard("this is the front", "this is the back");
System.out.println(test.getFront() + test.getBack());
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("hey.cardset"));
oos.writeObject(test);
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("hey.cardset"));
NoteCard n1 = (NoteCard) ois.readObject();
System.out.println(n1.getFront() + n1.getBack());
}
catch(Exception e) {
e.printStackTrace();
}
我浏览了整个互联网并翻阅了几本书,但一无所获。感谢您的帮助!
【问题讨论】:
-
确保您的
NoteCard类实现了java.io.Serializable并且它的字段也这样做,或者它们使用原始类型声明。
标签: java serialization