2012-09-09 190 views
2

所以标题几乎总结了我的问题,但我不知道我在做什么错误至于代码。当我写入Android中的文件时,它覆盖了以前的文件

这里就是我写的文件snipbit:

   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。如果你们需要我发布更多的代码让我知道。我很困惑,为什么这不是Context.MODE_PRIVATE工作:(

回答

9

相反,使用Context.MODE_APPEND,这种模式追加到现有文件,而不是删除它。(更多细节上的in the openFileOutput docs。)

+0

我认为这解决了它!它现在展示的一切文件中,现在弄清楚为什么它仍然只显示任务之一listView。感谢您的帮助!:) – cj1098

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(); 
+0

调用th在BufferedWriter上的''close()'方法应该关闭这个文件,所以你不需要再关闭它。 – LocalPCGuy

相关问题