追加到文本文件失败的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()
。
有人能告诉我为什么会发生这种情况吗?
答
要写入文件并附加FileOutPutStream
和OutPutStreamWriter
的创建实例,然后使用append
方法OutputStreamWriter
将数据追加到文件中。
FileOutputStream fOut = new FileOutputStream(myFile,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut,true);
myOutWriter.append()
第二个参数表示文本是否应该追加到现有文件中。
答
随着由Rahil2952给出的建议,我需要摆脱这一行:
fOutA = mContext.openFileOutput(textFileName, mContext.MODE_APPEND);
我不需要oneFileOutput
并设置其模式MODE_APPEND
。当append
设置为true
时,FileOutputStream
本身附加到现有文件。我也不需要使用OutputStreamWriter
。
我试过了,但没有什么区别! –