Saving And Loading Object Arrays

Started by
4 comments, last by RLS0812 11 years, 8 months ago
I have written some code, which saves and loads object arrays to / from file.
I would like to know if this test code is correct, and if there is any way to improve it.
The goals of this test code:
1: - Create object arrays
2: - Save object arrays
3: - Load object arrays

[Note:] The objects being used here are just for testing.
[source lang="java"]import java.io.*;

public class Main {

public static void main(String[] args){
// Simulate Unknown Number Of Objects
String[] cc = {"One","Two","Three","Four"};
// Create The Dump Array
String_Object[] DA = new String_Object[cc.length];
// Create Loading Array
String_Object[] LA;
File file = new File("EXP.sav");
int x= 0;
// Create Object Array
while (x != cc.length){
String_Object STR = new String_Object(cc[x]);
DA[x] = STR;
x ++;
}
x = 0;
// Save Object Array
try{
FileOutputStream SO = new FileOutputStream(file);
ObjectOutputStream save = new ObjectOutputStream(SO);
save.writeObject(DA);
save.close();
}
catch(Exception e){System.out.println(e);}
// Load Object Array
//if (file.exists() ){}
try{
FileInputStream SO = new FileInputStream(file);
ObjectInputStream save = new ObjectInputStream(SO);
LA = (String_Object[]) save.readObject();
save.close();
while (x != LA.length){
LA[x].out();
x ++;
}}
catch(Exception e){System.out.println(e);}
x = 0;
//else{System.out.println("Error Finding File");}
}}

// ========== //

// This Class Is Here To Simulate An Object
public class String_Object implements java.io.Serializable{
String st;
public String_Object (String xx){
st = xx;
}
public void out(){
System.out.println(st);
}}

[/source]

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Advertisement
Looks good to me. Something I would comment on is to flush a output/input stream before closing it.

So Eg:
[source lang="java"]save.writeObject(DA);
save.flush();
save.close();[/source]

This just makes things safer when closing files.

Hope this helped :)

~Ben
Seems all right to me. There are a few minor issues. Idiomatically one would use a finally block for closing the file streams. A Serializable class should consider having a known serialVersionUID, though this means that you need to be concious when serialized classes become incompatible. You also need to understand that Java will eagerly serialise the entire object graph, thus you need a mechanism for controlling how much of the graph is serialised (using the "transient" keyword) and how to rebuild the full graph from the partially saved graph.

When I used Java in the past for this, I tried to isolate the serialization from the actual objects of interest. That is, I would create an inner serialised class which contained just enough information to re-construct the overall object. This object acted as a kind of "factory", which when passed a "context" object was able to rebuild the full object, including restoring some references that would not be possible to save.

As an example, imagine a simple "game" that consists of little dust motes that spawn at the top of the screen and fade over time. I have just written this code right now, it has neither been compiled nor tested.

Let us imagine we are using some helper classes from other libraries:

// Possibly from some physics or game library
public class Vec2 {
public float x;
public float y;
}


// Possibly from some game or graphics library
public class Texture {
// ...
}

Note that these classes might be provided by a third party and might not be serializable.

Now here is a basic game object class we want to be able to serialize:

public class DustMote {


private static final float InitialLifetime = 60;

private final Vec2 position = new Vec2();
private final Texture texture;
private float life;

public DustMote(Vec2 position, Texture texture) {
this.position.set(position);
this.texture = texture;
this.life = InitialLifetime;
}

// ...
}

You can imagine some simple functionality to decrement the life field as time progresses and to draw the texture in the appropriate position. The actual game logic is irrelevant here.

Let us create a few interfaces to allow us to define what we want to achieve:

public interface GameContext {
public Texture getTexture(String name);
}


public interface Saveable {
public Restorable save();
}

public interface Restorable extends Serializable {
public Saveable restore(GameContext gameContext);
}

The Saveable will be implemented by the game object. The Restorable will be a simple immutable object containing just the fields of interest. The GameContext is the connection that allows us to reconnect the revived objects correctly into the object graph. In this case, it allows the game objects to retrieve other objects, in this case textures.

Here is what our game object might become:

public class DustMote implements Saveable {


private static final float InitialLifetime = 60;

private final Vec2 position = new Vec2();
private final Texture texture;
private float life;

public DustMote(Vec2 position, GameContext context) {
this(position, InitialLifetime, context);
}

private DustMote(Vec2 position, long life, GameContext context) {
this.position.set(position);
this.texture = context.getTexture("dust-mote");
this.life = life;
}

// ...

@Override
public Restorable save() {
return new DustModeState(this);
}

private static class DustMoteState implements Restorable {

private static final long serialVersionUID = 1L;

private final float x;
private final float y;
private final float life;

public DustMoteState(DustMote dustMote) {
this.x = dustMote.position.x;
this.y = dustMote.position.y;
this.life = dustMote.life;
}

@Override
public DustMote restore(GameContext context) {
Vec2 position = new Vec2(x, y);
return new DustMote(position, life, context);
}
}

}

The advantage of this approach is that it separates the serialised state from the current game state. Thus you don't need to weaken the game object's invariants just to support reviving the object. We have also removed the problem of worrying about whether our libraries have taken serialization into account.

When we want to save the game, the game just iterates through each Saveable, calling the save() method - the returned objects can be sent to the ObjectOutputStream. During loading, you can iterate through the ObjectInputStream, casting each returned value to a Restorable and calling the restore() object on it. The returned object would be added to some kind of collection in a "game world" object, or similar.

I'm not saying this is the best way, but it avoids some problems with directly serializing the game objects while being reasonably quick to get up and running, compared to hand writing serialisation routines.
Thank you for that.

Is there any easy to serialize bufferedImage ?

I think this will work, but haven't tested it yet

public class Image_Storage(BuferedImage Bi implements Serializable{
int width; int height; int[] pixels;
public ImagenPerso(BufferedImage Bi) {
width = Bi.getWidth();
height = Bi.getHeight();
pixels = new int[width * height];
int[] tmp=Bi.getRGB(0,0,width,height,pixels,0,width);
}
public BufferedImage getImage() {
BufferedImage Bi = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
Bi.setRGB(0,0,width,height,pixels,0,width);
return Bi;
}
}

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

Have you considered saving it as a standard image format - e.g. PNG?

Have you considered saving it as a standard image format - e.g. PNG?

What I am trying to do, is condense many images and files that belong together into one file.
Each "glob" file would contain the user sprite sheets, user background tile sheets, user midi files, user made scripts, and user created maps ...

The goal is to easily share data with users over a socket server / client , and add a layer of security to user generated material.

The issues I have to deal with:
1: All user generated material is unique
2: All user generated maps must be accessible to other users using socket server / client
3: All user generated content has to have some sort of protection to make it harder to steal.
4: Normal formats will be .png - .midi
5: Custom formats will be .scr ( custom scripting language i have developed(hashmap) ) - .ovw ( over world map( 2d array) ) - .map ( map files 5 layer 2 array ) - .sho ( shops (hashmap) ) - .itm ( items ( hashmap ) ) - .npc ( NPCs ( hashmap ) ) - .que ( quests ( hashmap ) ) - .eve ( events ( hashmap ) ) - .pls (player statistics ( hashmap ) )

I cannot remember the books I've read any more than the meals I have eaten; even so, they have made me.

~ Ralph Waldo Emerson

This topic is closed to new replies.

Advertisement