所以标题几乎总结了我的问题,但我不确定就代码而言我做错了什么。
这是我写入文件的 fragment :
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.append(assignmentTitle + "\n" + assignmentDate + "\n");
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
//catch errors opening file
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
编辑:这是我每次调用 Activity 时从文件中读取的地方
private void readDataFromFile() {
try {
//Opens a file based on the file name stored in FILENAME.
FileInputStream myIn = openFileInput(FILENAME);
//Initializes readers to read the file.
InputStreamReader inputReader = new InputStreamReader(myIn);
BufferedReader BR = new BufferedReader(inputReader);
//Holds a line from the text file.
String line;
//currentAssignment to add to the list
Assignment currentAssignment = new Assignment();
while ((line = BR.readLine()) != null) {
switch (index) {
case 0:
//Toast.makeText(this, line, Toast.LENGTH_LONG).show();
currentAssignment.setTitle(line);
index++;
break;
case 1:
//Toast.makeText(this, Integer.toString(assignmentListIndex), Toast.LENGTH_LONG).show();
currentAssignment.setDate_due(line);
Statics.assignmentList.add(assignmentListIndex, currentAssignment);
index = 0;
assignmentListIndex++;
currentAssignment = new Assignment();
break;
default:
Toast.makeText(this, "error has occured", Toast.LENGTH_SHORT).show();
break;
}
}
BR.close();
} catch (IOException e) {
e.printStackTrace();
}
}
当用户点击创建一个新任务时,这是一个函数。当他们单击作业上的保存按钮时,应该将该作业保存到一个文件中,然后我稍后阅读它并将其显示在 listView 中。它正在做的是在 listView 中显示第一项,当我创建一个新任务时,它会覆盖保存文件中的先前文本并在 listView 中替换它。如果你们需要我发布更多代码,请告诉我。我很困惑为什么这不起作用:(
最佳答案
而不是 Context.MODE_PRIVATE
, 使用 Context.MODE_APPEND
.此模式附加到现有文件而不是删除它。 (有关这些 in the openFileOutput
docs 的更多详细信息。)
关于android - 当我在 android 中写入文件时,它会覆盖以前存在的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12336181/