如何在java中的文本文件中添加文本?

时间:2012-11-01 10:04:36

标签: java

  

可能重复:
  How to append text to an existing file in Java

我想将数据添加到文本文件中。所以它是一个接一个......所以像:

1
2
3
<add more here>

但我不想删除文件中的文字。这是我正在使用atm的代码,但它取代了文件中的内容。有人可以告诉我如何做我问的问题。感谢。

    FileWriter fstream = new FileWriter("thefile.txt");
    BufferedWriter out = new BufferedWriter(fstream);
    out.write("blabla");
    out.close();
      }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
   }
}

1 个答案:

答案 0 :(得分:6)

使用此

FileWriter fstream = new FileWriter("thefile.txt",true);

解释

public FileWriter(String fileName, boolean append) throws IOException

构造一个FileWriter对象,给定一个带有布尔值的文件名,指示是否附加写入的数据。