[英]How to save an object into a file, so that i can load it later?
我一直試圖將一個對象(在我的情況下為一個級別)保存到文件中,以便以后可以再次加載它。 基本上只是一個保存/加載功能。 我無法使它正常工作。我一直得到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);
可以使用“序列化/反序列化”來完成。 將此作為第一種方法:
http://www.wikihow.com/Serialize-an-Object-in-Java
還可以嘗試在您喜歡的搜索引擎(很有可能是google hehe)上使用“ serialziation”關鍵字進行搜索。 有很多庫在如此高級的api中執行此過程。 另外,還有許多庫可以使用強大的功能來完成此任務。 例如通過數據庫進行序列化。 有時,序列化是使用JSON完成的(因為這可能是更通用的方式)。 享受序列化! :-)
編輯:還搜索JSON,漂亮的工具
忘記在OutPutStream代碼中添加以下行:
Level levelX = new Level();
這解決了它創建的非常小的保存游戲的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.