سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top