[英]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. 因此,可以说我有一个要使用PrintWriter写入的txt文件。 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. 我猜测这与每次调用该方法时都会创建一个新的PrintWriter或新的File的事实有关,但是在main方法中仅创建一个实例也无法正常工作。
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)
. 为此,请使用
new FileWriter("myfile.txt", true)
。 You can then wrap a PrintWriter around that if desired. 然后,如果需要,可以将PrintWriter包装在其周围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.