简体   繁体   中英

Android - Save to a text file

I am trying to write text to a file but i cant seem to get it to work.

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


    }

I have looked around and it seems i cant call openFileOutput() with out the context but have no idea "Context con = getApplicationContext()" will not work as im outside of a Activity. it just tells me that getapplicationcontext is undefined for the type. Can anyone help me out here?

You will have to pass the context from the calling activity:

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

How to use this from an Activity:

YOUR_UTIL_CLASS.saveState(this);

The following won't work:

Context con = getApplicationContext();

Reason: getApplicationContext() is a method that belongs to ContextWrapper . Class Activity extends ContextWrapper and thus has access to this method. Method saveState(..) probably resides in a utility class. getApplicationContext() isn't defined there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM