java 如何覆盖现有的 .txt 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26785315/
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 overwrite an existing .txt file
提问by mirzak
I have an application that creates a .txt file. I want to overwrite it. This is my function:
我有一个创建 .txt 文件的应用程序。我想覆盖它。这是我的功能:
try{
String test = "Test string !";
File file = new File("src\homeautomation\data\RoomData.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}else{
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
What should I put in the else clause, if the file exists, so it can be overwritten?
如果文件存在,我应该在 else 子句中放什么,以便可以覆盖它?
回答by Dici
You don't need to do anything particular in the else clause. You can actually open a file with a Writer
with two different modes :
您不需要在 else 子句中做任何特别的事情。你实际上可以Writer
用两种不同的模式打开一个文件:
- default mode, which overwrites the whole file
- append mode (specified in the constructor by a boolean set to
true
) which appends the new data to the existing one
- 默认模式,覆盖整个文件
- 追加模式(在构造函数中通过设置为 的布尔值指定
true
)将新数据追加到现有数据
回答by peter.petrov
Just call file.delete()
in your else block. That should delete the file, if that's what you want.
只需调用file.delete()
您的 else 块即可。如果这是您想要的,那应该删除该文件。
回答by zmf
You don't need to do anything, the default behavior is to overwrite.
您不需要做任何事情,默认行为是覆盖。
No clue why I was downvoted, seriously... this code will always overwrite the file
不知道为什么我被否决了,说真的……这段代码总是会覆盖文件
try{
String test = "Test string !";
File file = new File("output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
回答by aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
构造一个 FileWriter 对象,给定一个带有布尔值的文件名,指示是否附加写入的数据。
The Below one line code will help us to make the file empty.
下面一行代码将帮助我们将文件清空。
FileUtils.write(new File("/your/file/path"), "")
The Below code will help us to delete the file .
下面的代码将帮助我们删除文件。
try{
File file = new File("src\homeautomation\data\RoomData.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}