这是在 Java 中重写文件内容的最佳方法吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1016278/
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
Is this the best way to rewrite the content of a file in Java?
提问by Ankur
I want to rewrite the contents of a file.
我想重写文件的内容。
What I have thought of so far is this:
到目前为止我想到的是:
- Save the file name
- Delete the existing file
- Create a new empty file with the same name
- Write the desired content to the empty file
- 保存文件名
- 删除现有文件
- 新建一个同名的空文件
- 将所需内容写入空文件
Is this the best way? Or is there a more direct way, that is, not having to delete and create files, but simply change the content?
这是最好的方法吗?或者有没有更直接的方式,就是不用删除和创建文件,直接改变内容?
采纳答案by Stobor
To overwrite file foo.log with FileOutputStream:
用 FileOutputStream 覆盖文件 foo.log:
File myFoo = new File("foo.log");
FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
// false to overwrite.
byte[] myBytes = "New Contents\n".getBytes();
fooStream.write(myBytes);
fooStream.close();
or with FileWriter :
或使用 FileWriter :
File myFoo = new File("foo.log");
FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
// false to overwrite.
fooWriter.write("New Contents\n");
fooWriter.close();
回答by Matthew Flaschen
Unless you're just adding content at the end, it's reasonable to do it that way. If you are appending, try FileWriterwith the append constructor.
除非您只是在最后添加内容,否则这样做是合理的。如果要追加,请尝试使用带有追加构造函数的FileWriter。
A slightly better order would be:
稍微好一点的顺序是:
- Generate new file name (e.g. foo.txt.new)
- Write updated content to new file.
- Do atomic rename from foo.txt.new to foo.txt
- 生成新文件名(例如 foo.txt.new)
- 将更新的内容写入新文件。
- 将 foo.txt.new 原子重命名为 foo.txt
Unfortunately, renameTo is not guaranteedto do atomic rename.
不幸的是,renameTo不能保证进行原子重命名。
回答by drfloob
You'll want to open a File read-write, so:
您需要以读写方式打开文件,因此:
RandomAccessFile raf = new RandomAccessFile("filename.txt", "rw");
String tmp;
while (tmp = raf.readLine() != null) {
// Store String data
}
// do some string conversion
raf.seek(0);
raf.writeChars("newString");
回答by Sev
In the below example, the "false" causes the file to be overwritten, true would cause the opposite.
在下面的例子中,“false”会导致文件被覆盖,true 会导致相反的结果。
File file=new File("C:\Path\to\file.txt");
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));
String body = "new content";
outstream.write(body.getBytes());
outstream.close();
回答by jnt30
I would highly recommend using the Apache Common's FileUtil for this. I have found this package invaluable. It's easy to use and equally important it's easy to read/understand when you go back a while later.
我强烈建议为此使用 Apache Common 的 FileUtil。我发现这个包非常宝贵。它易于使用,同样重要的是,当您稍后返回时易于阅读/理解。
//Create some files here
File sourceFile = new File("pathToYourFile");
File fileToCopy = new File("copyPath");
//Sample content
org.apache.commons.io.FileUtils.writeStringToFile(sourceFile, "Sample content");
//Now copy from source to copy, the delete source.
org.apache.commons.io.FileUtils.copyFile(sourceFile, fileToCopy);
org.apache.commons.io.FileUtils.deleteQuietly(sourceFile);
More information can be found at: http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
更多信息可以在:http: //commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
回答by Lakshmi
There are times when one may want to keep a huge empty file so as to avoid extra cost of the OS allocating space on need basis. This is generally done by databases, Virtual machines and also in batch programs that process and write bulk data. This would improve the performance of the application significantly. In these cases, writing a new file and renaming it would not really help. Instead, the empty file will have to be filled up. That is when one must go for the override mode.
有时,人们可能希望保留一个巨大的空文件,以避免操作系统根据需要分配空间的额外成本。这通常由数据库、虚拟机以及处理和写入批量数据的批处理程序完成。这将显着提高应用程序的性能。在这些情况下,编写一个新文件并重命名它并没有真正的帮助。相反,必须填充空文件。那是人们必须进入覆盖模式的时候。
回答by Vadzim
GuavaFiles.write"Overwrites a file with the contents of a byte array":
Guava Files.write“用字节数组的内容覆盖文件”:
Files.write(bytes, new File(path));