2012-01-05 83 views
1

我真的很新的android開發,我的第一個項目是一個簡單的遊戲,至少有一個顯示和一個邏輯部分。我想添加一個保存功能到遊戲中,但是我在實現時遇到了問題。Android和ObjectOutputStream資源文件

我願做這種方式,用一個ObjectOutputStream(只是重要的部分是包括)

String filename = "res/raw/testfile.txt"; 
try 
{ 
    FileOutputStream fileout = new FileOutputStream(filename); 
    ObjectOutputStream out = new ObjectOutputStream(fileout); 
    out.writeObject(...logic objects...); 
} 
catch (Exception ex) 
{ 
    //show the error message 
} 

但我總是得到一個錯誤消息說至極,說:「沒有這樣的文件。」 。即使我在原始目錄中創建了「testfile.txt」,它也會顯示相同的錯誤。

請幫幫我,我做錯了什麼?

+0

「沒有這樣的文件...」,這可能意味着路徑不正確。 – 2012-01-05 18:30:21

+0

[This](http://stackoverflow.com/questions/1239026/how-to-create-a-file-in-android)可以幫助你。 :-) – micha 2012-01-05 18:30:51

回答

2

用文件名創建一個File對象,然後檢查文件是否存在。如果沒有,則創建該文件。如果是這樣,您可以覆蓋或提示用戶是否要覆蓋它。然後將File對象傳遞給FileOutputStream而不是文件名。類似這樣的:

String filename = "res/raw/testfile.txt"; 
try 
{ 
    File file = new File(filename); 
    if (!file.exists()) { 
     if (!file.createNewFile()) { 
      throw new IOException("Unable to create file"); 
     } 
    // else { //prompt user to confirm overwrite } 

    FileOutputStream fileout = new FileOutputStream(file); 
    ObjectOutputStream out = new ObjectOutputStream(fileout); 
    out.writeObject(...logic objects...); 
} 
catch (Exception ex) 
{ 
    //show the error message 
} 

還要確保關閉輸出流以防止任何資源泄漏。

享受!