追加到文本文件失败的Android

追加到文本文件失败的Android

问题描述:

我试图创建一个简单的文本文件,我成功地做,通过下面的代码:追加到文本文件失败的Android

   file=new File(mContext.getExternalFilesDir(null), generateFileName()); 
       fop=new FileOutputStream(file); 
       timeString="Method executed in:"+formatTime(executionTime)+"secs"; 
       contentInBytes=timeString.getBytes(); 
       startString="start()".getBytes(); 
       stopString="stop()".getBytes(); 
       fop.write(startString); 
       fop.write(System.getProperty("line.separator").getBytes()); 
       fop.write(contentInBytes); 
       fop.write(System.getProperty("line.separator").getBytes()); 
       fop.write(stopString); 
       fop.flush(); 
       fop.close(); 

       Log.d("write","Done writing."); 

当我尝试相同的文字再次追加到它,旧文本被清除,导致一个空的文本文件。

这是我试过的文字追加:

 fOutA=new FileOutputStream(file); //I also tried: new FileOutputStream(myFile,true); 
     fOutA = mContext.openFileOutput(textFileName, mContext.MODE_APPEND); 
     timeString="Method executed in:"+formatTime(executionTime)+"secs"; 
     contentInBytes=timeString.getBytes(); 
     startString="start()".getBytes(); 
     stopString="stop()".getBytes(); 
     fOutA.write(startString); 
     fOutA.write(System.getProperty("line.separator").getBytes()); 
     fOutA.write(contentInBytes); 
     fOutA.write(System.getProperty("line.separator").getBytes()); 
     fOutA.write(stopString); 
     fOutA.flush(); 
     fOutA.close(); 
     Log.d("append","Done appending."); 

textfileName PARAM在附加代码块是相同的写代码块的generatedFileName()

有人能告诉我为什么会发生这种情况吗?

要写入文件并附加FileOutPutStreamOutPutStreamWriter的创建实例,然后使用append方法OutputStreamWriter将数据追加到文件中。

FileOutputStream fOut = new FileOutputStream(myFile,true); 
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut,true); 
myOutWriter.append() 

第二个参数表示文本是否应该追加到现有文件中。

+0

我试过了,但没有什么区别! –

随着由Rahil2952给出的建议,我需要摆脱这一行:

fOutA = mContext.openFileOutput(textFileName, mContext.MODE_APPEND); 

我不需要oneFileOutput并设置其模式MODE_APPEND。当append设置为true时,FileOutputStream本身附加到现有文件。我也不需要使用OutputStreamWriter