Search code examples
javaarraysmultidimensional-arrayfilereaderfilewriter

Transferring a 2D array into a file and back


I've looked around at similar questions, but I'm still stuck on this bit of code.

public class MasterMindSaveLoad extends Board {
    public void saveGame() {
        ObjectOutputStream oos = new ObjectOutputStream(new FileWriter("saveGame.txt"));
            for (int i=0; i<numPegs; i++) {
                for (int j=0; j<numColours; j++) {
                    oos.writeObject(Board[i][j]);
                }
            }
            for (int i=0; i<numPegs; i++) {
                for (int j=0; j<numColours; j++) {
                    oos.writeObject(Feedback[i][j]);
                }
            }

        }
    public void loadGame(String savedGame) {
        try {

        } catch (MasterMindFileFormatException e) {

        } catch (IOException e) {

        }
    }
}

I have been given a really rough layout for saving a 2D array into a file and reading back from it. I was not sure how to go about it, and this is as much as I've got so far. I have to actually save two 2D arrays, and then when reading, I have to put them back into their own arrays again.


Solution

  • you can handle your 2D array as an object

    Board[][] board = new Board[][]; 
    Object ob = board;
    

    then you can simply serialize and deserialize this object with the ObjectInputStream

    ObjectOutputStream oos = new ObjectOutputStream(new FileWriter("saveGame.txt"));
    oos.writeObject(board); //simply write the entire object
    

    to retrive the data you just read it back:

    ObjectInputStream ois = new ObjectInputStream(new FileReader("saveGame.txt"));
    Object o = ois.read();
    board = (Board[][])o; //cast back to 2d array
    

    use this technique for the Feedback[][] as well

    have a look at this tutorial: http://www.journaldev.com/2452/java-serialization-example-tutorial-serializable-serialversionuid