写入txt文件,但不覆盖
问题描述:
我有一个小问题,看起来很简单(我个人认为是这样),但是我找不到答案。但至少我不知道如何解决它。写入txt文件,但不覆盖
当我点击保存按钮时,我写了一些行到.txt文件。 然后,当我输入其他内容时,再次点击保存,它会覆盖我的第一行。
但我希望它写在一个新的行。另外,当我关闭并重新启动应用程序并再次点击保存时,它必须再次将文本保存在新行中。
所以基本上:我如何写文本到.txt文件,而不覆盖以前的行。 我可以写入一个文件,所以这不是问题,但只有如何不覆盖。
这是我的代码的“小”部分:
public void Data_save_contacts(View v) {
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
try {
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt"));
writer_contact.write("Perceel "+str_boer_teler_nummer+" = "+str_boer_teler);
writer_contact.newLine();
} catch (IOException e) {
System.err.println(e);
}
}
请把我的好方向。
感谢不已,Bigflow
答
你要做
writer_contact =新的BufferedWriter(新FileWriter的(根+ “/Save/Contacten.txt",true));
正如Java文档中说:
FileWriter
public FileWriter(File file,
boolean append)
throws IOException
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning
答
尝试:
public FileWriter (File file, boolean append)
设置append
到true
答
那么给这只是一个小小的代码的(我假设你的分块出来,以便没有透露其他地区)是我可疑的事情是,你打开文件的根目录+“/Save/Contacten.txt”在非附加模式。第一次调用它时,会创建并写入文件。随后您调用它时,它会找到该文件并重新创建(或删除内容),然后写入该文件。
尝试使用:第一次
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt", true));
当然你打开/创建,你会希望它是假的(除非你总是要追加,如果该文件已经存在)的文件。
给一个旋转。
答
你可以检查文件是否退出?
或者你也可以附加旧文件。
如果不退出然后只创建一个新的。
现在我觉得很愚蠢......但是谢谢! – Bigflow 2012-04-06 08:43:28
别担心!很高兴有帮助;) – Ant4res 2012-04-06 08:50:53