Android 写入txt文件,但不覆盖
我有一个小问题,看起来很简单(我个人认为是),但我找不到答案。但至少我不知道如何修复它 当我点击Save按钮时,我将一些行写入.txt文件。 然后,当我键入其他内容并再次单击“保存”时,它会覆盖我的第一行 但我希望它写在新的一行。此外,当我再次关闭并重新启动应用程序,并再次点击“保存”时,它必须再次将文本保存在新行上 因此,基本上:如何将文本写入.txt文件,而不覆盖前面的行。 我可以写一个文件,所以这不是问题,只是如何不覆盖 这是我代码的“小”部分:Android 写入txt文件,但不覆盖,android,file,overwrite,Android,File,Overwrite,我有一个小问题,看起来很简单(我个人认为是),但我找不到答案。但至少我不知道如何修复它 当我点击Save按钮时,我将一些行写入.txt文件。 然后,当我键入其他内容并再次单击“保存”时,它会覆盖我的第一行 但我希望它写在新的一行。此外,当我再次关闭并重新启动应用程序,并再次点击“保存”时,它必须再次将文本保存在新行上 因此,基本上:如何将文本写入.txt文件,而不覆盖前面的行。 我可以写一个文件,所以这不是问题,只是如何不覆盖 这是我代码的“小”部分: public void Data_s
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试试:
public FileWriter (File file, boolean append)
将append
设置为true
尝试:
public FileWriter (File file, boolean append)
将追加
设置为真
您必须执行的操作
writer_contact=new BufferedWriter(新文件编写器(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
你必须这样做
writer_contact=new BufferedWriter(新文件编写器(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
考虑到这只是您代码的一小部分(我假设您将其分块以避免泄露其他部分),我怀疑您正在以非附加模式打开文件root+“/Save/Contacten.txt”。第一次调用它时,将创建并写入该文件。以后调用它时,它会找到文件,并重新创建(或删除内容)然后写入 尝试使用:
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt", true));
当然,第一次打开/创建文件时,您会希望它为false(除非您总是希望在文件已经存在时追加)
试一试。好吧,这只是您代码的一小部分(我假设您将其分块以避免泄露其他部分),我怀疑您正在以非附加模式打开文件root+“/Save/Contacten.txt”。第一次调用它时,将创建并写入该文件。以后调用它时,它会找到文件,并重新创建(或删除内容)然后写入 尝试使用:
writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt", true));
当然,第一次打开/创建文件时,您会希望它为false(除非您总是希望在文件已经存在时追加)
旋转一下。您可以检查文件是否退出 或者也可以附加旧文件
如果不退出,则只创建一个新文件。您可以检查文件是否退出 或者也可以附加旧文件
如果没有退出,则只创建一个新的。别担心!很高兴能帮上忙;)别担心!很高兴能帮上忙;)