Java overwriting an existing output file

两盒软妹~` 提交于 2019-12-10 12:35:31

问题


My program is currently using

FileOutputStream output = new FileOutputStream("output", true);

A while loop creates the output file if it is not yet created and appends some data to this file for every iteration of the while loop using

 output.write(data).  

This is fine and is what I want.

If I run the program again the file just doubles in size as it appends the exact information to the end of the file. This is not what I want. I would like to overwrite the file if I run the program again.


回答1:


This documentation suggests that the parameter you're passing is the append parameter.

the signature looks like the following

FileOutputStream(File file, boolean append)

You should set that parameter to false since you don't want to append.

FileOutputStream output = new FileOutputStream("output", false);



回答2:


I would like to overwrite the file if I run the program again.

Pass false as 2nd argument, to set append to false:

FileOutputStream output = new FileOutputStream("output", false);

Check out the constructor documentation:

If the second argument is true, then bytes will be written to the end of the file rather than the beginning.




回答3:


Or you could just delete the file if it's there, and then always create it and job done.



来源:https://stackoverflow.com/questions/17957849/java-overwriting-an-existing-output-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!