Reputation: 521
I want a save/load function in my class. I created a private subclass where I store every data that I want to save.
public class MyClass {
private class Progress implements Serializable {
private static final long serialVersionUID = 1L;
boolean val1 = true;
int val2 = 0;
ArrayList<String> list = new ArrayList<String>();
}
private Progress progress = new Progress();
public void loadProgress() {
progress = null;
try
{
FileInputStream fileIn = new FileInputStream("./tmp/progress.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
progress = (Progress) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Progress class not found");
c.printStackTrace();
return;
}
}
public void saveProgress() {
try
{
File f = new File("./tmp/progress.ser");
f.getParentFile().mkdirs();
FileOutputStream outputstream = new FileOutputStream(f);
ObjectOutputStream out = new ObjectOutputStream(outputstream);
out.writeObject(progress);
out.close();
outputstream.close();
}catch(IOException i) {
i.printStackTrace();
}
}
}
But when I want to try this code, it gives me java.io.NotSerializableException exception in the saveProgress() method, and because of this, the loadProgress() method is not working too. How can I serialize this class?
Upvotes: 0
Views: 78
Reputation: 27476
Outer class also needs to be Serializable
, because each inner class has an implicit reference to the outer class.
So to solve this you need to mark MyClass
as Serializable
or make Progress
a static class. Static classes don't have reference to the outer class.
Upvotes: 1
Reputation: 25950
When you try serializing an instance of an inner class, the outer instance will also be serialized. In your case, MyClass
is not serializable so it won't work. There are two possible workarounds:
Progress
a static nested classMyClass
serializableI would argue in favor of the first approach whenever it's possible since it serializes less data and therefore has better performance and space efficiency.
Upvotes: 1