当我写入android中的文件时,它会覆盖以前的文件

cj1*_*098 2 file-io android file

所以标题几乎总结了我的问题,但我不确定我做错了什么代码.

这是我写入文件的片段:

                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();
                }
Run Code Online (Sandbox Code Playgroud)

编辑:这是我每次调用活动时从文件中读取的内容

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();
            }
    }
Run Code Online (Sandbox Code Playgroud)

这是在用户点击时创建新作业的函数.当他们单击赋值时的保存按钮时,它应该将该赋值保存到文件中,然后我稍后再读它并将其显示在listView中.它正在做的是显示listView中的第一项,当我创建一个新的赋值时,它会覆盖保存文件中的前一个文本并将其替换为listView.如果你们需要我发布更多代码请告诉我.我很困惑,为什么这不起作用:(

Eri*_*ric 9

而不是Context.MODE_PRIVATE,使用Context.MODE_APPEND.此模式附加到现有文件而不是删除它.(关于文档中的openFileOutput更多细节.)