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

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未定义。有谁可以帮我离开这里吗?

最佳答案

您将必须通过调用活动传递上下文:

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()

关于java - Android-保存到文本文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19062746/

10-10 17:52