如何将android字符串保存到文本文件然后设置为textview?

时间:2011-11-01 15:59:48

标签: android io android-file

我正在尝试将字符串保存到onPause方法中的txt文件中,然后将保存的字符串设置为textview,但我遇到了问题。我不需要在onResume方法中设置字符串。主要问题是让IO在Android上运行,谢谢。

String fileNameString="savedString.txt";
String textToSave = "PLEASE SAVE ME";
EditText editText;    

public void onResume() {
    super.onResume();
    TextView textViewString = (TextView)findViewById(R.id.item);
    try {
        InputStream in = openFileInput(fileNameString);
        if (in!=null) {
            InputStreamReader tmp = new InputStreamReader(in);
            BufferedReader reader=new BufferedReader(tmp);
            String str;
            StringBuffer buf=new StringBuffer();

            while ((str=reader.readLine()) != null) {
                buf.append(str+"\n");
            }
            textViewString.setText(str);
            in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
    }
    catch (Throwable t) {
        Toast
            .makeText(this,"Exception: "+t.toString(),2000)
            .show();
    }
}
public void onPause() {
    super.onPause();
    try {
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput(fileNameString,0));
        out.write(textToSave);
        out.close();
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: " +t.toString(), 2000)
            .show();
    }
}

1 个答案:

答案 0 :(得分:3)

如果您希望跨会话使变量保持不变,最好使用SharedPreference而不是将其存储到文本文件中。