java 追加到文件android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5987012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
append to file android
提问by Carlos Barbosa
hey there, i need to append to my file but it is not working, it keeps overwriting the file, can anyone please tell me what is wrong:
嘿,我需要附加到我的文件中,但它不起作用,它不断覆盖文件,任何人都可以告诉我出了什么问题:
public void generateNoteOnSD(String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "AdidasParticipants");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, "participants.txt");
BufferedWriter bW;
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write(sBody);
bW.newLine();
bW.flush();
bW.close();
//Toast.makeText(mContext, "Tus datos han sido guardados", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
// importError = e.getMessage();
// iError();
}
}
Thanks in advance.
提前致谢。
回答by nicholas.hauschild
You can fix it by changing the line where you assign the BufferedWriter
:
您可以通过更改您分配的行来修复它BufferedWriter
:
bW = new BufferedWriter(new FileWriter(gpxfile, true));
When you open a file using the FileWriter
constructor that only takes in a File
, it will overwrite what was previously in the file. Supplying the second parameter as true
tells the FileWriter
that you want to append to the end of it.
当您使用FileWriter
仅接受 a的构造函数打开文件时File
,它将覆盖文件中先前的内容。提供第二个参数 astrue
告诉FileWriter
您要附加到它的末尾。