Reputation: 85
I am making a Game which is basically 2D minecraft, and I am creating a new Object with 3 parameters for each block (X , Y , Object Type). The game itself works, however I cant save it, because it crashes every time I use the save function. (java.io.NotSerializableException) - why not???
So here I have my Array List, which stores Objects:
public static ArrayList<Objects> list = new ArrayList<Objects>();
And here is my Class called Objects:
public class Objects{
public int ObjectX;
public int ObjectY;
public int ObjectName;
public int ObjectSize = Game.ObjectSize;
public Objects(int x, int y, int n) {
ObjectX=x;
ObjectY=y;
ObjectName=n;
}
public void render(Graphics g){
if(ObjectX*ObjectSize-Game.x+ObjectSize > 0 && ObjectX*ObjectSize-Game.x < Game.w && ObjectY*ObjectSize-Game.y+ObjectSize > 0 && ObjectY*ObjectSize-Game.y < Game.h){
if(ObjectName!=1){
g.setColor(Color.BLACK);
g.fillRect(ObjectX*ObjectSize-Game.x, ObjectY*ObjectSize-Game.y,ObjectSize,ObjectSize);
}
if(ObjectName==2){
g.setColor(Color.GREEN);
g.fillRect(ObjectX*ObjectSize +1-Game.x, ObjectY*ObjectSize +1-Game.y,ObjectSize-2,ObjectSize-2);
}
if(ObjectName==3){
g.setColor(new Color(139,69,19));
g.fillRect(ObjectX*ObjectSize +1-Game.x, ObjectY*ObjectSize +1-Game.y,ObjectSize-2,ObjectSize-2);
}
}
}
public void tick(){
}
}
So I tried a few things, however i cant get this to work??? I really need some help with this.
//write
public void save(String filename) throws FileNotFoundException {
doing = "Saving...";
try{
File file = new File(filename);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
}catch(IOException e){
e.printStackTrace();
}
SAVE=false;
}
Upvotes: 0
Views: 120
Reputation: 3660
Let's say I want to write an instance of Foo
to a file. I need to make Foo
implement Serializable
, like this:
public class Foo implements Serializable {}
If Foo
is serializable, every object inside Foo
must be too. If Foo
contains Bar
, Bar
must also implement Serializable
. If Bar
contains an ArrayList<Baz>
, Baz
must be serializable. ArrayList
is already serializable, so you don't have to worry about it.
Notice that you don't actually have to implement anything for an object to be serializable. You only have to mark it with the proper interface.
Upvotes: 1