【发布时间】:2012-02-24 02:53:39
【问题描述】:
有没有专家可以帮助我?在我的 Android 主要活动中,我试图将一个字符串保存到一个文件中,然后如果用户之前设置过它,然后再检索它。找不到任何与我正在做的事情接近的例子。我将不胜感激任何帮助!这是我崩溃的测试用例:
String testString = "WORKS";
String readString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FileOutputStream fos;
try {
fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
fos.write(testString.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File file = getBaseContext().getFileStreamPath("test.txt");
if (file.exists()) {
FileInputStream fis;
try {
fis = openFileInput("test.txt");
fis.read(readString.getBytes());
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
txtDate.setText(String.valueOf(readString));
} else {
// more code
}
}
}
【问题讨论】:
-
为什么要使用文件?尝试使用SharedPreferences - 更少的代码和混乱。