所以这个标题很好地总结了我的问题,但就代码而言,我不确定我做错了什么。
下面是我写入文件的代码片段:
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();
}Edit:这是我每次调用活动时从文件中读取的地方
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();
}
}在函数中,当用户单击create a new assignment时。当他们单击作业上的保存按钮时,它应该将作业保存到一个文件中,然后我稍后读取它并将其显示在listView中。它所做的是显示listView中的第一项,当我创建一个新的分配时,它会覆盖保存文件中以前的文本,并在listView中替换它。如果你们需要我发布更多的代码,请告诉我。我很困惑,为什么这个不起作用:
发布于 2012-09-09 11:00:59
使用Context.MODE_APPEND而不是Context.MODE_PRIVATE。此模式会附加到现有文件,而不是擦除该文件。(有关这些in the openFileOutput docs的更多详细信息。)
发布于 2012-09-09 11:19:11
我建议你像下面这样使用BufferedWriter类,而不是使用OutputStreamWriter类。
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();https://stackoverflow.com/questions/12336181
复制相似问题