0

I'm using txt files, creating them with the class PrintWriter. This allows me to print inside a txt file some content using println(...) method.

But now I need to add some content at the end of the list that I created. Like this:

PrintWriter writer = new PrintWriter("File.txt", "UTF-8");

writer.println("Hello");
writer.println("Josh!");

writer.close();

the result is a file like this:

Hello

Josh!

but what if I would like to add new words at the bottom of the text? I would prefer an overwriting of the file "File.txt" with the content updated?

Hello

Josh!

How are you?

I was thinking on something like, "Ok I have to add another line at the end, so read all the file, and write another file (with the same name and content) adding a new line at the end", but it seems too strange to do, I feel like there is another simple way to do it. Any other idea?

Matt
  • 773
  • 2
  • 15
  • 32

2 Answers2

1

Your suspicions are correct.

You should use try with resources (Java 7+):

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("File.txt", true)))) {
    out.println("How are you?");
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file). Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out. But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

Also this allows you to append to a file, rather than replacing the whole file, on every run. Lastly, try with resources means you do not have to call .close(), it's done for you! Grabbed from here

Community
  • 1
  • 1
benscabbia
  • 17,592
  • 13
  • 51
  • 62
1

You could simply use a FileWriter instead, it has an append mode that you can enable:

    FileWriter writer = new FileWriter("File.txt");

    writer.write("Hello\n");

    writer.write("Josh!\n");

    writer.close();

    writer = new FileWriter("File.txt", true);

    writer.append("Great!");

    writer.close();
simon
  • 1,095
  • 6
  • 11