Geoffroi
Geoffroi

Reputation: 144

PrintWriter deleting old contents of a txt file when writing

So lets say I have a txt file that I want to write to with a PrintWriter. How come the following code deletes the old contents of the file everytime its called?

Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Test {

    public static void main(String[] args) {
        writeToFile("foo");
        writeToFile("bar");
    }

    public static void writeToFile(String text) {
        try {
            PrintWriter printer = new PrintWriter(new File("myTextFile.txt"));
            printer.println("Your text is:" + text);
            printer.close();
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        }
    }

}

Output:

Your text is:bar

I'm guessing its something to do with the fact that I'm creating a new PrintWriter or a new File every time the method is being called, but having only one instance being created in the main method failed to work as well.

Upvotes: 3

Views: 8638

Answers (2)

Nnamdi
Nnamdi

Reputation: 71

Doing something like:

FileWriter fileWriterName = new FileWriter("myfile.txt", true);
PrintWriter printWriterName = new PrintWriter(fileWriterName);

should work.

Calling

printWriterName.println("Hello"); 

should add a "Hello" line to myfile.txt without erasing what was there before.

thanks @keshlam

Upvotes: 0

keshlam
keshlam

Reputation: 8058

If you want to add to a file's contents, you need to explicitly open the file for append; the default in most languages is overwrite.

To do so in Java, use new FileWriter("myfile.txt", true). You can then wrap a PrintWriter around that if desired.

Upvotes: 4

Related Questions