How can I save the state of my program and then load it?

I'm trying to save and reload the state of my Swing program, which in this case is a Minesweeper game. My code for the board is below.

package mines;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Board extends JPanel {

    public static void main (String[] args)  {}
    private final int NUM_IMAGES = 13;
    private final int CELL_SIZE = 15;

    private final int COVER_FOR_CELL = 10;
    private final int MARK_FOR_CELL = 10;
    private final int EMPTY_CELL = 0;
    private final int MINE_CELL = 9;
    private final int COVERED_MINE_CELL = MINE_CELL + COVER_FOR_CELL;
    private final int MARKED_MINE_CELL = COVERED_MINE_CELL + MARK_FOR_CELL;

    private final int DRAW_MINE = 9;
    private final int DRAW_COVER = 10;
    private final int DRAW_MARK = 11;
    private final int DRAW_WRONG_MARK = 12;

    private int[] field;
    private boolean inGame;
    private int mines_left;
    private Image[] img;
    private int mines = 40;
    private int rows = 16;
    private int cols = 16;
    private int all_cells;
    private JLabel statusbar;

    public Board(JLabel statusbar) {

        this.statusbar = statusbar;

        img = new Image[NUM_IMAGES];

        for (int i = 0; i < NUM_IMAGES; i++) {
            img[i] =
                (new ImageIcon(this.getClass().getResource((i)
                    + ".png"))).getImage();
        }

        setDoubleBuffered(true);

        addMouseListener(new MinesAdapter());

        newGame();
    }


    public void newGame() {

        Random random;
        int current_col;

        int i = 0;
        int position = 0;
        int cell = 0;

        random = new Random();
        inGame = true;
    mines_left = mines;

    all_cells = rows * cols;
    field = new int[all_cells];

    for (i = 0; i < all_cells; i++)
        field[i] = COVER_FOR_CELL;

    statusbar.setText(Integer.toString(mines_left));


    i = 0;
    while (i < mines) {

        position = (int) (all_cells * random.nextDouble());

        if ((position < all_cells) &&
            (field[position] != COVERED_MINE_CELL)) {


            current_col = position % cols;
            field[position] = COVERED_MINE_CELL;
            i++;

            if (current_col > 0) { 
                cell = position - 1 - cols;
                if (cell >= 0)
                    if (field[cell] != COVERED_MINE_CELL)
                        field[cell] += 1;
                cell = position - 1;
                if (cell >= 0)
                    if (field[cell] != COVERED_MINE_CELL)
                        field[cell] += 1;

                cell = position + cols - 1;
                if (cell < all_cells)
                    if (field[cell] != COVERED_MINE_CELL)
                        field[cell] += 1;
            }

            cell = position - cols;
            if (cell >= 0)
                if (field[cell] != COVERED_MINE_CELL)
                    field[cell] += 1;
            cell = position + cols;
            if (cell < all_cells)
                if (field[cell] != COVERED_MINE_CELL)
                    field[cell] += 1;

            if (current_col < (cols - 1)) {
                cell = position - cols + 1;
                if (cell >= 0)
                    if (field[cell] != COVERED_MINE_CELL)
                        field[cell] += 1;
                cell = position + cols + 1;
                if (cell < all_cells)
                    if (field[cell] != COVERED_MINE_CELL)
                        field[cell] += 1;
                cell = position + 1;
                if (cell < all_cells)
                    if (field[cell] != COVERED_MINE_CELL)
                        field[cell] += 1;
            }
        }
    }
}


public void find_empty_cells(int j) {

    int current_col = j % cols;
    int cell;

    if (current_col > 0) { 
        cell = j - cols - 1;
        if (cell >= 0)
            if (field[cell] > MINE_CELL) {
                field[cell] -= COVER_FOR_CELL;
                if (field[cell] == EMPTY_CELL)
                    find_empty_cells(cell);
            }

        cell = j - 1;
        if (cell >= 0)
            if (field[cell] > MINE_CELL) {
                field[cell] -= COVER_FOR_CELL;
                if (field[cell] == EMPTY_CELL)
                    find_empty_cells(cell);
            }

        cell = j + cols - 1;
        if (cell < all_cells)
            if (field[cell] > MINE_CELL) {
                field[cell] -= COVER_FOR_CELL;
                if (field[cell] == EMPTY_CELL)
                    find_empty_cells(cell);
            }
    }

      cell = j - cols;
    if (cell >= 0)
        if (field[cell] > MINE_CELL) {
            field[cell] -= COVER_FOR_CELL;
            if (field[cell] == EMPTY_CELL)
                find_empty_cells(cell);
        }

       cell = j + cols;
       if (cell < all_cells)
        if (field[cell] > MINE_CELL) {
            field[cell] -= COVER_FOR_CELL;
            if (field[cell] == EMPTY_CELL)
                find_empty_cells(cell);
           }

          if (current_col < (cols - 1)) {
           cell = j - cols + 1;
             if (cell >= 0)
               if (field[cell] > MINE_CELL) {
                field[cell] -= COVER_FOR_CELL;
                if (field[cell] == EMPTY_CELL)
                    find_empty_cells(cell);
            }

           cell = j + cols + 1;
            if (cell < all_cells)
               if (field[cell] > MINE_CELL) {
                field[cell] -= COVER_FOR_CELL;
                if (field[cell] == EMPTY_CELL)
                    find_empty_cells(cell);
            }

          cell = j + 1;
           if (cell < all_cells)
            if (field[cell] > MINE_CELL) {
                field[cell] -= COVER_FOR_CELL;
                if (field[cell] == EMPTY_CELL)
                    find_empty_cells(cell);
               }
        }

       }

      public void paint(Graphics g) {

       int cell = 0;
        int uncover = 0;


        for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {

            cell = field[(i * cols) + j];

            if (inGame && cell == MINE_CELL)
                inGame = false;

            if (!inGame) {
                if (cell == COVERED_MINE_CELL) {
                    cell = DRAW_MINE;
                } else if (cell == MARKED_MINE_CELL) {
                    cell = DRAW_MARK;
                } else if (cell > COVERED_MINE_CELL) {
                    cell = DRAW_WRONG_MARK;
                } else if (cell > MINE_CELL) {
                    cell = DRAW_COVER;
                }


            } else {
                if (cell > COVERED_MINE_CELL)
                    cell = DRAW_MARK;
                else if (cell > MINE_CELL) {
                    cell = DRAW_COVER;
                    uncover++;
                }
            }

            g.drawImage(img[cell], (j * CELL_SIZE),
                (i * CELL_SIZE), this);
        }
       }


      if (uncover == 0 && inGame) {
        inGame = false;
        statusbar.setText("Game won");
      } else if (!inGame)
        statusbar.setText("Game lost");
       }




     class MinesAdapter extends MouseAdapter {
       public void mousePressed(MouseEvent e) {

        int x = e.getX();
        int y = e.getY();

        int cCol = x / CELL_SIZE;
        int cRow = y / CELL_SIZE;

        boolean rep = false;


          if (!inGame) {
            newGame();
            repaint();
          }


         if ((x < cols * CELL_SIZE) && (y < rows * CELL_SIZE)) {

            if (e.getButton() == MouseEvent.BUTTON3) {

                if (field[(cRow * cols) + cCol] > MINE_CELL) {
                    rep = true;

                    if (field[(cRow * cols) + cCol] <= COVERED_MINE_CELL) {
                        if (mines_left > 0) {
                            field[(cRow * cols) + cCol] += MARK_FOR_CELL;
                            mines_left--;
                            statusbar.setText(Integer.toString(mines_left));
                        } else
                            statusbar.setText("No marks left");
                    } else {

                        field[(cRow * cols) + cCol] -= MARK_FOR_CELL;
                        mines_left++;
                        statusbar.setText(Integer.toString(mines_left));
                    }
                }

            } else {

                if (field[(cRow * cols) + cCol] > COVERED_MINE_CELL) {
                    return;
                }

                if ((field[(cRow * cols) + cCol] > MINE_CELL) &&
                    (field[(cRow * cols) + cCol] < MARKED_MINE_CELL)) {

                    field[(cRow * cols) + cCol] -= COVER_FOR_CELL;
                    rep = true;

                    if (field[(cRow * cols) + cCol] == MINE_CELL)
                        inGame = false;
                    if (field[(cRow * cols) + cCol] == EMPTY_CELL)
                        find_empty_cells((cRow * cols) + cCol);
                }
            }

            if (rep)
                repaint();

            }
        }
    }
}

There are any number of possible choices...

You could

Use the Properties API, which provides save and load functionality.

The API works like a Map, allowing you to store key/value pairs, which you can save and load as required.

The API only allows you to store String values, so you would need to convert non-String values manually.

Just remember to save them as the API does not automatically persist the changes

Take a look at Properties for more details.

You could

Roll you own XML file or use something like JAXB which allows you to bind properties of object and export/import them to/from XML

This approach would be more flexible then using Properties, but introduces a level of complexity

You Could

Use the Preferences API, which allows you to store String and primitive values, with out the need to perform any type of converstion.

The Preferences API also automatically loads and stores it's content, but it will do so where it wants to, so you lose control over where the content is stored.

You Could

Use a stand alone/single user database like H2 or HSQLDB for example. It's a little more complicated but does take care of the basic storage requirements.

It would also require additional time to update should you change your requirements, over something like using Properties or Preferences and might be a little overkill if all you are storing is the cell data...IMHO

You Could

Try using object serialization, but the API was never meant for the long term storage of object states and carrie it's bag of problems and I would personally avoid it, but that's me.


In a Java app., there are a great variety of ways to go about serializing app. data.

  • For applets there are cookies.
  • For apps. launched using JWS, the PersistenceService
  • Any app. might use the Preferences API.

All those forms of serialization are meant for stuff that can be encoded into a String based name and value.

  • A Properties file is also good for name/value type info.
  • For more complex data I would create a bean and use XMLEncoder/XMLDecoder.
  • A Zip file is good for serializing data that might be in many different forms (e.g. part XML, part Properties, some screenshot images..).

If using the properties, XML or Zip archive, a good place to save the info. is a sub-directory of user.home. It is reproducible and the app. should have read/write permissions.