1

So I have a JFrame with a button that accesses this method to write a String to a text file:

 public static void writeTest(String item) {
    File file = new File (directory + "TestFile.txt");
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(item);
            out.newLine();
            out.close();
        } catch (IOException e) {

        }
   }

This part works fine, but if I click the button again, it will always write over the first line, even though I have the newLine(); there. I even tried putting newLine(); before AND after out.write(); , but it just replaces the first line of the file with a blank space, and then writes the 'item' String on the second line. I want it to write a line of String, save it in the text file, and when I write a new line, it ADDS a line of text to the file, not overwrite it.

David
  • 179
  • 1
  • 1
  • 10
  • 1
    possible duplicate of [BufferedWriter to write to file](http://stackoverflow.com/questions/11543338/bufferedwriter-to-write-to-file) – Danny. Feb 27 '15 at 14:11
  • possible duplicate of [Java FileWriter with append mode](http://stackoverflow.com/questions/1225146/java-filewriter-with-append-mode) – Kenster Feb 27 '15 at 15:06

2 Answers2

3

Write file in append mode:

BufferedWriter out = new BufferedWriter(new FileWriter(file, true));

Here, new FileWriter(file, true), true is flag for append mode

0

Open FileWriter in append mode

MGorgon
  • 2,547
  • 23
  • 41