我一直在尝试将一个对象(在我的例子中是一个关卡)保存到一个文件中,以便稍后可以再次加载它。基本上只是一个保存/加载功能。我无法让它工作..我不断收到一个 5 字节的文件,这对于其中应该包含的内容来说似乎太小了。我知道它可能与可序列化有关,但我不知道是什么。这是我当前的代码:
(顺便说一句,我将关卡硬编码到程序中,因为我还不知道如何将其正确保存到文件中。尽管这是目标......)
public class BufferSaveGames {
public void saveGameOutputStream(Level level) throws FileNotFoundException {
ObjectOutputStream output;
try {
output = new ObjectOutputStream((new FileOutputStream("SaveGame.dat")));
output.writeObject(level);
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
以及正在加载的第二个级别:(例如删除不需要的代码)
public class Level implements MouseListener, Serializable {
private Level currentLevel;
private int aantalPoppetjesOpLevel;
private String oplossing;
private int timer;
JPanel[][] levelGrid;
Poppetje[] lijstPoppetjes;
public Level() throws IOException{
levelGrid = new JPanel[5][5];
lijstPoppetjes = new Poppetje[5];
for (int a=0;a<5;a++) {
for (int b=0;b<5;b++) {
levelGrid[a][b] = new JPanel();
levelGrid[a][b].setSize(100,100);
levelGrid[a][b].setVisible(true);
levelGrid[a][b].setLayout(null);
levelGrid[a][b].setOpaque(false);
levelGrid[a][b].addMouseListener(this);
}
}
//bovenste rij
levelGrid[0][0].setLocation(10,10);
levelGrid[0][1].setLocation(112,10);
levelGrid[0][2].setLocation(214,10);
levelGrid[0][3].setLocation(316,10);
levelGrid[0][4].setLocation(418,10);
Poppetje roodPoppetje = new Poppetje("Rood", 4, 4);
Poppetje oranjePoppetje = new Poppetje("Oranje", 0, 4);
Poppetje groenPoppetje = new Poppetje("Groen", 1, 2);
Poppetje paarsPoppetje = new Poppetje("Paars", 2, 1);
Poppetje geelPoppetje = new Poppetje("Geel", 3, 3);
//Poppetje blauwPoppetje = new Poppetje("Blauw");
int tempA = roodPoppetje.getLocatieX(roodPoppetje);
int tempB = roodPoppetje.getLocatieY(roodPoppetje);
levelGrid[tempA][tempB].add(roodPoppetje);
lijstPoppetjes[0] = roodPoppetje;
lijstPoppetjes[0].addMouseListener(this);
tempA = oranjePoppetje.getLocatieX(oranjePoppetje);
tempB = oranjePoppetje.getLocatieY(oranjePoppetje);
levelGrid[tempA][tempB].add(oranjePoppetje);
lijstPoppetjes[1] = oranjePoppetje;
lijstPoppetjes[1].addMouseListener(this);
最佳答案
这可以通过“序列化/反序列化”来完成。将此作为第一种方法:
http://www.wikihow.com/Serialize-an-Object-in-Java
还可以尝试在您最喜欢的搜索引擎(很可能是谷歌呵呵)上使用“serialziation”关键字进行搜索。有很多库在如此高级的 api 中执行此过程。还有很多库可以做到这一点,并且具有强大的用途;就像通过数据库进行序列化一样。有时序列化是使用 JSON 完成的(因为它可能是一种更通用的方法)。享受连载吧! :-)
编辑:还搜索 JSON,漂亮的工具
关于java - 如何将对象保存到文件中,以便稍后加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23160481/