我正在寻找一种将实例化的类(对象)输出到文件的方法。我尝试过使用 FileStream,但它似乎不起作用。经过研究,似乎我需要使用一种称为“序列化”的技术。我完全迷失在这个话题上。有人可以为我调试这段代码吗?我有一种预感,这个问题正在发生,因为我试图在普通类中序列化一个抽象类。抽象类是 java.util.Calendar。
class CalendarL implements java.io.Serializable{
private static final long serialVersionUID = 1L;
java.util.Calendar calendar;
CalendarL (int date, int month, int year){
calendar.set (Calendar.DATE, date);
calendar.set (Calendar.MONTH, month);
calendar.set (Calendar.YEAR, year);
}
}
class IO {
protected CalendarL reader() throws IOException, ClassNotFoundException{
FileInputStream data = new FileInputStream("data.dat");
ObjectInputStream dataObject = new ObjectInputStream(data);
CalendarL calendar = (CalendarL)dataObject.readObject();
dataObject.close();
data.close();
return calendar;
}
protected void output(CalendarL calendar) throws IOException, WriteAbortedException, NotSerializableException {
new FileOutputStream("data.dat").close();
FileOutputStream data = new FileOutputStream("data.dat");
ObjectOutputStream dataObject = new ObjectOutputStream(data);
dataObject.writeObject(calendar);
dataObject.close();
data.close();
}
}
这是我得到的错误:
Exception in thread "main" java.io.NotSerializableException: hotelres.ClientL
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)