1

I've been searching and can't get a clue on how to do this. I'm creating a block-based game, let's say 3x3 blocks on screen, each block has a int associated to know which type it is:

int[][] blocksArray = {
    { 0, 0, 0 }
    { 0, 0, 1 }
    { 0, 0, 0 }
};

What I basically want to do is save like 50 multi-dimensional arrays like this one into a file let's say "levels.txt" just like this:

int[][] level1 = {
    { 0, 0, 0 }
    { 0, 0, 1 }
    { 0, 0, 0 }
};
...
int[][] level50 = {
    { 0, 0, 0 }
    { 0, 0, 0 }
    { 0, 0, 0 }
};

Is this a good way of approaching the problem? Are there better methods?

I really don't want to make a string of my arrays and save them into shared prefs, because I will need to edit a lot of level arrays manually and I want to have this format, or maybe a very similar way to do it?

2
  • The quick and dirty version would be to create an Object that holds all your Arrays and then use an ObjectOutputStream and call writeObject(..) passing that object. Commented Nov 22, 2012 at 14:11
  • I was thinking about that, like looping a 3 dimensional int array that would contain other 2 dimensional arrays. As you say, this is the quick and dirty way, any better idea? Thanks! Commented Nov 22, 2012 at 18:18

1 Answer 1

1

You can save your arrays in a file using java.io.ObjectOutputStream();

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file"));
    oos.writeObject(level1);
    ...
    oos.writeObject(level50);

and then read your arrays back:

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file"));
    level1 = (int[]][])ois.readObject();
    ...
    level50 = (int[]][])ois.readObject();

If it is really what you want

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer! However, I have another question: If I just setup a new class, let's say "levels.class", in which I contain all arrays, and then just add a reference to levels.arrayName, would that be an effective approach?
As I understand your Level class is going to hold somehow all level arrays. In this case it should be Level implements java.io.Serializable then you can call writeObject(level) only once, writeObject will analize Level and will save all what's inside. Same for readObject.
What I ment is to actually load the variables directly; lets say the user chooses the first level, the mainBlocksArray = Levels.array1; for example. Would this be practical? Are there any better approaches?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.