Android - 保存到文本文件

时间:2013-09-28 03:01:41

标签: java android java-io

我正在尝试将文本写入文件,但我似乎无法让它工作。

public static void saveState(){

        String data = age + "," ;
        FileOutputStream fos;
        Context con = getApplicationContext();
        try {
            fos = con.openFileOutput("state", 0);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
            outputStreamWriter.write(data);
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        } 


    }

我环顾四周似乎无法在上下文中调用openFileOutput()但不知道“Context con = getApplicationContext()”将无法在Activity之外工作。它只是告诉我getapplicationcontext未定义类型。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您必须从调用活动传递上下文:

public static void saveState(Context context){

    String data = age + "," ;
    FileOutputStream fos;

    try {
        fos = context.openFileOutput("state", 0);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

如何在活动中使用此功能:

YOUR_UTIL_CLASS.saveState(this);

以下内容不起作用:

Context con = getApplicationContext();

原因:getApplicationContext()是属于ContextWrapper的方法。类Activity扩展ContextWrapper,因此可以访问此方法。方法saveState(..)可能驻留在实用程序类中。那里没有定义getApplicationContext()