Java 如何让 PrintWriter 覆盖旧文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24112096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make PrintWriter overwrite old file
提问by Alexandre Vandermonde
I'm working on a project where I need to print some data to a file. During debugging phase, I would like to overwrite the old textfile so that I don't have to delete the old file just to see the result of some changes that I've made in the code. Currently, the new output data is either added to the old data in the file, or the file doesn't change at all (also, why could this be?). The following is, in essence, the printing part of the code:
我正在处理一个需要将一些数据打印到文件的项目。在调试阶段,我想覆盖旧的文本文件,这样我就不必删除旧文件只是为了查看我在代码中所做的一些更改的结果。目前,新的输出数据要么添加到文件中的旧数据,要么文件根本不改变(另外,为什么会这样?)。下面,本质上就是代码的打印部分:
public class Test {
public static void main(String[] arg) {
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream("Foo.txt", true));
} catch (Exception e){}
double abra = 5;
double kadabra = 7;
pw.printf("%f %f \n", abra, kadabra);
pw.close();
}
}
Thanks!
谢谢!
采纳答案by dasblinkenlight
Pass false
to the append
parameterto overwrite the file:
传递false
给append
参数以覆盖文件:
pw = new PrintWriter(new FileOutputStream("Foo.txt", false));
Passing true
for the second parameter indicates that you want to append to the file; passing false
means that you want to overwrite the file.
传递true
给第二个参数表示要追加到文件中;传递false
意味着您要覆盖文件。
回答by Neeraj Kumar
Simply pass second parameter false.
只需传递第二个参数false。
Also you can use other writer object instead of FileOutputStream as you are working with txt file. e.g
您也可以在使用 txt 文件时使用其他 writer 对象而不是 FileOutputStream。例如
- pw = new PrintWriter(new FileWriter("Foo.txt", false));
- pw = new PrintWriter(new BufferedWriter(new FileWriter("Foo.txt", false)));
- pw = new PrintWriter(new FileWriter("Foo.txt", false));
- pw = new PrintWriter(new BufferedWriter(new FileWriter("Foo.txt", false)));
while working with txt/docs files we should go for normal writer objects( FileWriter or BufferedWriter) and while working with binary file like .mp3 , image, pdf we should go for Streams ( FileOutputStream or OutputStreamWriter ).
在使用 txt/docs 文件时,我们应该使用普通的 writer 对象(FileWriter 或 BufferedWriter),而在使用二进制文件(如 .mp3、image、pdf)时,我们应该使用 Streams(FileOutputStream 或 OutputStreamWriter)。