2012-09-05 22 views
0

我有我的Activity類中加載和保存文件的代碼。它工作正常。代碼保存了cFavretClass的內容。我正在清理代碼,所以我將文件I/O移到了cFavret類中。你需要在Activity類中有文件I/O嗎?

我無法獲得編譯的代碼。現在我收到一個錯誤,說openFileOutput is undefined in type cFavrets

我假設這個方法是在谷歌活動類中聲明的? 這是否意味着所有的文件I/O都必須在活動類中?

boolean Save() 
{ 
    String FILENAME = "hello_file"; 

    try { 
    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
    fos.write(buffer); 
    fos.close(); 
    } 
    // just catch all exceptions and return false 
    catch (Throwable t) { 
    return false; 
    }  
    return true; 
} 

boolean Load() 
{ 
    String FILENAME = "hello_file"; 
    try { 
    FileInputStream fos = openFileInput(FILENAME); 
    buffer[0]=0; 
    fos.read(buffer); 
    fos.close(); 
    } 
    // just catch all exceptions and return false 
    catch (Throwable t) { 
    // maybe file does not exist, try creating it 
    return false; 
    } 
    return true; 
} 

回答

1

這是否意味着所有的文件I/O必須在活動課?

沒有,但有問題的方法是從上下文調用 - 只是通過上下文到這個cFavretClass的構造函數(或方法本身,如果你喜歡):

Context mContext; 
public cFavretClass(Context context) { 
    mContext = context; 
} 

... 
    // in your methods: 
    mContext.openFileOutput(FILENAME); 
+0

嗨,在Activty類中,我怎麼能得到上下文???我正在嘗試Context mContext; mContext = Context;不工作 –

+0

活動是上下文 - 只需傳遞「this」即可 – JRaymond

0

由於JRaymond解釋,openFileOutputContext的方法,其中Activity是派生。此方法是特殊的,因爲它允許您創建文件,這些文件是私有到您的應用程序。

您也可以使用普通的Java I/O類來寫入外部存儲器(SD卡),但這些文件將被每個人讀取。

相關問題