문제

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