如何将对象保存到文件中,以便以后加载?

时间:2014-04-18 18:59:45

标签: java object serialization file-io

我一直试图将一个对象(我的情况下是一个级别)保存到一个文件中,这样我以后可以再次加载它。基本上只是一个保存/加载功能。我无法让它工作..我不断得到一个5字节的文件,这似乎很小,应该在它的内容。我知道它可能与Serializable有关,但我不知道是什么。这是我目前的代码:

(顺便说一句,我把关卡硬编码到程序中,因为我不知道如何将它正确保存到文件中。虽然这是目标......)

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);

2 个答案:

答案 0 :(得分:1)

可以通过“序列化/反序列化”来完成。看看这是第一种方法:

http://www.wikihow.com/Serialize-an-Object-in-Java

还可以尝试使用您最喜爱的搜索引擎上的“serialziation”关键字进行搜索(很可能是google hehe)。有很多库在如此高级别的api中执行此过程。此外,还有很多库通过强大的用途来实现这一目标;喜欢通过数据库序列化。有时序列化是使用JSON完成的(因为它可能是一种更通用的方法)。享受序列化! : - )

编辑:还搜索JSON,漂亮的工具

答案 1 :(得分:0)

忘了在OutPutStream代码中添加以下行:

            Level levelX = new Level();

这解决了它创建的非常小的保存游戏的问题。