【问题标题】:Write to txt file, but not overwrite写入txt文件,但不覆盖
【发布时间】:2012-04-19 22:12:24
【问题描述】:

我遇到了一个小问题,看起来很简单(我个人认为是这样),但我找不到答案。但至少我不知道如何解决它。

当我点击保存按钮时,我将一些行写入 .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

【问题讨论】:

    标签: android file overwrite


    【解决方案1】:

    你必须这样做

    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】:

    尝试:

    public FileWriter (File file, boolean append)
    

    append 设置为true

    【讨论】:

      【解决方案3】:

      好吧,这只是您的一小部分代码(我假设您将其分块以免泄露其他部分),我怀疑您正在打开文件根目录 + "/Save /Contacten.txt" 处于非附加模式。第一次调用它时,文件被创建并写入。随后您调用它,它会找到该文件,并重新创建(或删除内容)然后写入该文件。

      尝试使用:

      writer_contact = new BufferedWriter(new FileWriter(root + "/Save/Contacten.txt", true));
      

      当然,当你第一次打开/创建文件时,你会希望它是 false (除非你总是想在文件已经存在的情况下追加)。

      试一试。

      【讨论】:

        【解决方案4】:

        你可以检查文件是否存在?

        或者您也可以附加旧文件。

        如果不退出则只创建一个新的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-28
          • 1970-01-01
          • 2011-05-08
          • 2019-10-17
          • 1970-01-01
          • 2012-04-15
          • 2012-06-18
          相关资源
          最近更新 更多