2010-12-09 135 views
14

我創建了一個由自定義對象組成的數組列表。基本上,用戶將創建一個類,每次創建一個類時,新的演講(我的自定義對象)將被添加到數組列表中。我需要保存生成的數組列表,這樣即使應用程序重新啓動,用戶的類也將被保存。如何存儲自定義對象的數組列表?

從我的理解,我必須讓我的類可序列化。但我到底該怎麼做?然後,一旦它的序列化,我該怎麼辦?

public class Lecture{ 

public String title; 
public String startTime; 
public String endTime; 
public String day; 
public boolean classEnabled; 

public Lecture(String title, String startTime, String endTime, String day, boolean enable){ 
    this.title = title; 
    this.startTime = startTime; 
    this.endTime = endTime; 
    this.day = day; 
    this.classEnabled = enable; 
} 
//Getters and setters below 

回答

11

你很幸運,你的所有類的成員已經serialzble所以你的第一步是說講座是序列化。

public class Lecture implements Serializable { 

    public String title; 
    public String startTime; 
    public String endTime; 
    public String day; 
    public boolean classEnabled; 

    public Lecture(String title, String startTime, String endTime, String day, boolean enable){ 
     this.title = title; 
     this.startTime = startTime; 
     this.endTime = endTime; 
     this.day = day; 
     this.classEnabled = enable; 
    } 

接下來,您需要創建一個默認的構造函數,因爲序列化似乎需要。最後一件事是你需要將你的對象寫入一個文件。我通常使用類似以下的東西。注意這是爲了保存遊戲狀態,所以你可能不想使用緩存目錄。

private void saveState() { 
    final File cache_dir = this.getCacheDir(); 
    final File suspend_f = new File(cache_dir.getAbsoluteFile() + File.separator + SUSPEND_FILE); 

    FileOutputStream fos = null; 
    ObjectOutputStream oos = null; 
    boolean   keep = true; 

    try { 
     fos = new FileOutputStream(suspend_f); 
     oos = new ObjectOutputStream(fos); 

     oos.writeObject(this.gameState); 
    } 
    catch (Exception e) { 
     keep = false; 
     Log.e("MyAppName", "failed to suspend", e); 
    } 
    finally { 
     try { 
      if (oos != null) oos.close(); 
      if (fos != null) fos.close(); 
      if (keep == false) suspend_f.delete(); 
     } 
     catch (Exception e) { /* do nothing */ } 
    } 
} 

讀回數據與寫入是非常對稱的,所以我已經將這個問題留給了這個答案。另外,對序列化對象還有很多警告,所以我建議你做一些谷歌搜索,並在一般情況下閱讀Java序列化。

+0

解釋減去,我用Google搜索的是找到你的答案! – l0gg3r 2014-03-15 15:34:50

13

我使用一個類的天氣應用程序我開發...

public class RegionList extends ArrayList<Region> {} // Region implements Serializeable 

爲了節省我用這樣的代碼......

FileOutputStream outStream = new FileOutputStream(Weather.WeatherDir + "/RegionList.dat"); 
ObjectOutputStream objectOutStream = new ObjectOutputStream(outStream); 
objectOutStream.writeInt(uk_weather_regions.size()); // Save size first 
for(Region r:uk_weather_regions) 
    objectOutStream.writeObject(r); 
objectOutStream.close(); 

注:之前我寫的地區對象,我寫一個int來保存列表的「大小」。

當我讀回我做到這一點...

FileInputStream inStream = new FileInputStream(f); 
ObjectInputStream objectInStream = new ObjectInputStream(inStream); 
int count = objectInStream.readInt(); // Get the number of regions 
RegionList rl = new RegionList(); 
for (int c=0; c < count; c++) 
    rl.add((Region) objectInStream.readObject()); 
objectInStream.close(); 
相關問題