Java创建一个新文件,或者覆盖现有文件 [英] Java create a new file, or, override the existing file
问题描述
我想要实现的是创建一个文件,而不管文件是否存在.
What I want to achieve is to create a file regardless of whether the file exists or not.
我尝试使用File.createNewFile()
,但这只会在该文件不存在的情况下创建该文件.我应该先使用File.delete()
然后使用File.createNewFile()
吗?
I tried using File.createNewFile()
but that will only create the file if it does not already exists. Should I use File.delete()
and then File.createNewFile()
?
或者有更清晰的方法吗?
Or is there a clearer way of doing it?
推荐答案
FileWriter的构造函数也需要两个参数:文件名和布尔值.布尔值指示是追加还是覆盖现有文件.这是两个Java FileWriter示例,显示了这一点:
FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:
Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file
这篇关于Java创建一个新文件,或者覆盖现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!