这是在 Java 中重写文件内容的最佳方法吗? [英] Is this the best way to rewrite the content of a file in Java?
本文介绍了这是在 Java 中重写文件内容的最佳方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想重写一个文件的内容.
I want to rewrite the contents of a 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?
推荐答案
用 FileOutputStream 覆盖文件 foo.log:
To overwrite file foo.log with FileOutputStream:
File myFoo = new File("foo.log");
FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
// false to overwrite.
byte[] myBytes = "New Contents
".getBytes();
fooStream.write(myBytes);
fooStream.close();
或使用 FileWriter :
or with FileWriter :
File myFoo = new File("foo.log");
FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
// false to overwrite.
fooWriter.write("New Contents
");
fooWriter.close();
这篇关于这是在 Java 中重写文件内容的最佳方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文