我遇到了一个问题,看起来很简单(我个人认为是这样),但我找不到答案。但至少我不知道如何解决它。
当我点击按钮保存时,我在.txt文件中写了一些行。 然后,当我输入其他内容,再次点击Save时,它会覆盖我的第一行。
但我希望它写在一个新的一行。此外,当我再次关闭并重新启动应用程序并再次点击保存时,它必须再次将文本保存在新行上。
基本上:如何在不覆盖前一行的情况下将文本写入.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
答案 0 :(得分:3)
尝试:
public FileWriter (File file, boolean append)
将append
设置为true
答案 1 :(得分:3)
你必须做
writer_contact = new BufferedWriter(new FileWriter(root +“/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
答案 2 :(得分:0)
嗯,鉴于这只是你的一些代码(我假设你把它分块以便不透露其他部分)我怀疑你正在进行的是你打开文件root +“/ Save /Contacten.txt“处于非追加模式。第一次调用它时,文件就会被创建并写入。随后您调用它,它会找到该文件,然后重新创建(或删除内容),然后写入它。
尝试使用:
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt", true));
当然,第一次打开/创建文件时,你会希望它是假的(除非你总是希望在文件已经存在时附加)。
给它一个旋转。
答案 3 :(得分:0)
您可以检查文件是否存在?
或者您也可以追加旧文件。
如果不存在,那么只创建新的。