0

I noticed when I want to write some text to a file, it always creates new file. Why is that? Why not 'append' the content? Does anyone have reasonable explanation?

I will demonstrate with super simple program:

try {
    FileWriter fileWrite = new FileWriter("a.txt");
    fileWrite.write("Aa");
    fileWrite.close();
}catch (IOException ioe){
    ioe.printStackTrace();
        }

try {
    FileWriter fileWriter = new FileWriter("a.txt");
    fileWriter.write("Bb");
    fileWriter.close();
}catch (IOException ioe){
    ioe.printStackTrace();
}

Now, what is the content of file 'a.txt'? It is not AaBb as I expected, but Bb. Can someone explain? Why does java behave this way? How can I understand this the easy way? :)

Ana Maria
  • 475
  • 2
  • 11
  • Operation you need is appending. Read this post [how to append text](https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – Lazar Đorđević Jul 20 '20 at 12:14
  • Try to use FileWriter constructor with two parameters: FileWriter fileWriter = new FileWriter("a.txt", true); see https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html – Vitaliy Tretyakov Jul 20 '20 at 12:14
  • Thank a lot guys, I know that, but why is this the default behavior? Why is it 'tied' to a file? – Ana Maria Jul 20 '20 at 14:59

0 Answers0