I am looking for a way to output an instantiated class, an Object to a file. I have tried using FileStream and it doesn’t seem to be working. After researching, it seems as though i need to use a technique called “serialization”. I’m absolutely lost on this topic. Would someone please debug this code for me? I have a hunch that the problem is occurring because I am trying to serialize an abstract class within a normal class. The abstract class is 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();
}
}
This is the error I get:
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)
That hunch is not correct. You serialize instances (not classes) and the class of an instance cannot be an abstract class. Besides, the
Calendarclass does implementSerializable… the javadoc says so.