从文件加载序列化对象时为空

时间:2019-02-04 00:26:08

标签: java serializable

我正在尝试将GameSave对象保存到文件中并从那里加载它。 GameSave(与引用的对象相同)实现了Serializable。加载的对象似乎为空。我没有任何错误。 我已经尝试解决这个问题超过一个星期了,没有结果。

GameSave类:

import java.io.Serializable;

/**
 * Stores all data of a game. Wraps game data like previous moves.
 */
public class GameSave implements Serializable {

    private Board board;
    private Color currentColor;

    public GameSave() {
        this.board = new Board();
        this.currentColor = Color.WHITE;
    }
}

保存对象的类:

import java.io.*;

/**
 * Backend to story game saves to a file backend
 */
public class FileBackendText implements Backend {
    /**
     * Load a game from the given save name
     *
     * @param saveName the name of the save
     * @return a {@link GameSave} instance; null if no save could be found
     */
    @Override
    public GameSave loadGame(String saveName) {

        createDirectories();

        GameSave gameSave;
        File file = new File("/saves/"+saveName+".ser");

        try {
            FileInputStream fileIn = new FileInputStream(file);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            gameSave = (GameSave) in.readObject();
            in.close();
            fileIn.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        System.out.println("Loaded: " + gameSave);

        return gameSave; //TODO: Load from file backend
    }

    /**
     * Creates the save data directories
     */
    private void createDirectories() {
        if(new File("/saves").mkdirs())
            System.out.println("Created save directories!");
    }

    /**
     * Save a {@link GameSave} instance to the backend
     *
     * @param gameSave  the name of the save
     * @param saveName  the game data to be stored
     * @param overwrite overwrite old data if given
     * @return was save successful. Not successful if file has to be overwritten and overwrite parameter is false
     */
    @Override
    public boolean saveGame(GameSave gameSave, String saveName, boolean overwrite) {

        createDirectories();

        File file = new File("/saves/"+saveName+".ser");

        System.out.println(file.getAbsolutePath());

        if(file.exists() && !overwrite)
            return false;

        try {
            FileOutputStream fileOut =
                    new FileOutputStream(file);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(gameSave);
            out.close();
            fileOut.close();
            System.out.printf("Game data saved in /saves/%s.ser\n",saveName);
        } catch (IOException i) {
            i.printStackTrace();
        }

        return true; //TODO: save to file backend
    }
}

所以我实际上想在调用load方法时有一个游戏保存对象,但是会为空。

0 个答案:

没有答案