Are you certain the arraylist was populated when you saved it? I’m only asking because I’ve done boneheaded things like that. I was able to do the following and it worked:
package serialtest;
import java.awt.Point;
import java.io.Serializable;
import java.util.ArrayList;
public class SaveLevel implements Serializable {
static final long serialVersionUID = 99999999999999L;
public ArrayList<Point> path = new ArrayList<Point>();
public String imagePath;
public SaveLevel(String imagePath){
this.imagePath=imagePath;
}
}
package serialtest;
import java.awt.Point;
import java.io.*;
import java.util.ArrayList;
public class SerialTest {
public static void main(String[] args) {
// Create some Dummy information
SaveLevel sLevel = new SaveLevel("Hi this is a test");
ArrayList<Point> points = new ArrayList<Point>();
points.add(new Point(1,1));
points.add(new Point(2,2));
points.add(new Point(3,3));
sLevel.path = points;
String fileName ="c:\\level.dat";
// Write the object to disk
try {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(sLevel);
out.close();
fileOut.close();
}catch(IOException i) {
i.printStackTrace();
}
// Make an empty saved level
SaveLevel newLevel = new SaveLevel("");
// Try to read the level back from the file
ObjectInputStream ois;
try {
FileInputStream fileIn = new FileInputStream(fileName);
ois = new ObjectInputStream(fileIn);
SaveLevel loadedLevel = (SaveLevel) ois.readObject();
newLevel = loadedLevel;
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// This should print out "Hi this is a test" and 3 points if it worked.
System.out.println(newLevel.imagePath);
System.out.println(newLevel.path);
}
}
This worked (the restored arraylist has 3 elements). The main difference is that I didn’t use the getResource method to create the objectinputstream.