I'm trying to implement loading and saving for a game I'm working on.
What I want to save is:
- A
char[][]
(bidimensional array/matrix) - An
ArrayList<Entity>
Entity is a super class for Dragon
, Hero
and Item
. All three of these types can be contained at once in the ArrayList
.
So far I have this:
package logic;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public final class LoadAndSave {
public static final transient boolean available = false;
public static final boolean serialize(Object obj) {
// Write to disk with FileOutputStream
FileOutputStream saveFile;
try {
saveFile = new FileOutputStream("game.sav");
} catch (FileNotFoundException e) {
return false;
}
// Write object with ObjectOutputStream
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(saveFile);
} catch (IOException e) {
//
return false;
}
// Write object out to disk
try {
objOut.writeObject(obj);
} catch (IOException e) {
return false;
}
return true;
}
public static final Object load() {
FileInputStream fileIn;
try {
fileIn = new FileInputStream("game.sav");
} catch (FileNotFoundException e1) {
return null;
}
// Read object using ObjectInputStream
ObjectInputStream objIn;
try {
objIn = new ObjectInputStream(fileIn);
} catch (IOException e) {
return null;
}
// Read an object
Object obj;
try {
obj = objIn.readObject();
} catch (IOException e) {
return null;
} catch (ClassNotFoundException e) {
return null;
}
return obj;
}
}
I think the code is pretty self-explanatory. Now for my questions:
- Will this code suffice?
- Do I need to implement specific serialization methods for
Dragon
,Item
andHero
? - How will the serialization mechanism deal with the fact that I have an
Entity
vector full of types that are notEntity
, but derived classes? Thanks for your time!
OK, all seems to be well, except for one the ArrayList
. It is either not getting saved or loaded (null pointer exception
when calling size()
).
What may this be due to?