所以标题几乎总结了我的问题,但是我不确定我做错了什么代码。
这是我写入文件的片段:
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();
}
编辑:这是我每次调用活动时从文件中读取的内容
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。如果你们需要我发布更多代码请告诉我。我很困惑为什么这不起作用:(
答案 0 :(得分:9)
而不是Context.MODE_PRIVATE
,请使用Context.MODE_APPEND
。此模式附加到现有文件而不是删除它。 (关于in the openFileOutput
docs的详细信息。)
答案 1 :(得分:0)
而不是使用OutputStreamWriter
类我建议您使用BufferedWriter
类,如下所示,
private File myFile = null;
private BufferedWriter buff = null;
myFile = new File ( "abc.txt" );
buff = new BufferedWriter ( new FileWriter ( myFile,true ) );
buff.append ( assignmentTitle );
buff.newLine ( );
buff.append ( assignmentDate );
buff.newLine ( );
buff.close();
myFile.close();