BlackCat BlackCat - 4 months ago 10
Java Question

Serializing/Deserializing an object with an ArrayList<String> within in Java

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?

Answer

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:

  • make Progress a static nested class
  • make MyClass serializable

I 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.