Reputation: 272
I have a program that adds PanelFurniture
objects to an ArrayList
. When i try to save the data in a file, it is giving me the exception java.io.NotSerializableException: PanelFurniture$1
. PanelFurniture
is the name of the class, and it implements Serializable
already, so I don't understand what the problem might be.
This is my code for writing the ArrayList to the file
if(ae.getSource() == commandButtons[5]) {
int x = 5 , y = 11;
File confidential = new File("secrets.txt");
PrintWriter output = null;
try {
saveFile = new FileOutputStream("myFile.dat");
save = new ObjectOutputStream(saveFile);
save.writeObject(orderList);
save.close();
System.out.println(orderList);
}
catch (Exception e){
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 4638
Reputation: 178
Your issue is linked to the subModel incluyed on your arraylist
For each model on your object, you must add "implements Serializable" and include the autogenerated "private static final long serialVersionUID "
by that way you can save and entire list without any exceptions
Upvotes: 0
Reputation: 8764
Your PanelFurniture
class, which is the content of your ArrayList
, needs to implement the Serializable
interface, as well as any anonymous inner classes (like PanelFurniture$1
), so Java doesn't know how to read/write this data to disk.
If you don't want to use serialization, you are probably wanting to do something like this... (psuedocode)
Create a FileOutputStream
for (each item in the ArrayList){
get the properties of the PanelFurniture object, and write them to the FileOutputStream.
eg. fos.writeLine(panelFurniture.getName() + "," + panelFurniture.getValue());
}
Close the FileOutputStream.
Upvotes: 2
Reputation: 52185
Taking a look at the JavaDoc for the writeObject() method:
Throws:
NotSerializableException - Some object to be serialized does not implement the java.io.Serializable interface.
Are you sure that the elements making up your ArrayList implement the Serializable
Interface?
Upvotes: 1
Reputation: 116246
PanelFurniture$1
refers to an anonymous inner class, which apparently does not implement Serializable
. So you should qualify the corresponding class member with transient
(or make it a local variable instead), as anonymous classes are not supposed to contain serializable data. If yours does, you should turn into a normal (named) inner class and have it implement Serializable
.
Upvotes: 4