0

Sorry if this was already asked but I am having some problems serializing classes I made. I have tested Strings and Array Lists but when I try a NoteCard, a class made of two Strings, I get errors when serializing and obviously deserializing. These are the errors I get when running the program.

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)

The code for the errors is the following:

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

I have looked all over the internet and looked through a few books and found nothing. Thanks for the help!

  • 1
    Make sure your `NoteCard` class implements `java.io.Serializable` and its fields also do it or they are declared using a primitive type. – Luiggi Mendoza May 22 '15 at 14:10

1 Answers1

1

Make sure NoteCard implements java.io.Serializable interface

public class NoteCard implements java.io.Serializable

and also if NoteCard contains other class members, then make sure they are also implementing java.io.Serializable.

When you want to serialize a class, always calculate a serialVersionUID, and most of the IDE's will do it for you. If you don't provide one, then java will do it for you when you serialize, but it's not recommended.

private static final long serialVersionUID = -3457676767677L;
K139
  • 3,654
  • 13
  • 17
  • *When you want to serialize a class, always calculate a serialVersionUID* that's not necessary at all, in fact that field is useless. – Luiggi Mendoza May 22 '15 at 14:13