我正在尝试保存一个gamesave对象到一个文件中并从那里加载它。gamesave(对于引用的对象也一样)实现可序列化。加载的对象似乎为空。我没有得到任何错误。我已经试着解决这个问题一个多星期了,但没有结果。
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方法时有一个game save对象,但是得到null。
暂无答案!
目前还没有任何答案,快来回答吧!