好的,所以我的文件输出有问题。当我没有启用附加“ true”时,文件将正确保存,但是我需要附加它。当发生切换时,程序崩溃。我试图写所有行(在不同的活动上),这似乎可行。我还将提供我正在使用的代码。我需要崩溃问题方面的帮助,关于为何将其添加到文件会导致此问题的任何想法?
写入文件:
void save(String x) throws IOException {
final String FILE_NAME = "database.txt";
FileOutputStream fos = null;// sucessfully writes 1 line to the file overwritting the old one
//FileOutputStream fos = new FileOutputStream(FILE_NAME,true); //crashes the app
fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
fos.write(x.getBytes());
Toast.makeText(this, "Database Updated!",
Toast.LENGTH_LONG).show();
}
从文件中读取
TextView thisTask = (TextView)findViewById(R.id.textView3);
final String FILE_NAME = "database.txt";
FileInputStream fis = null;
try {
fis = openFileInput(FILE_NAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
thisTask.setText(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}