这是用Java重写文件内容的最好方法吗? [英] Is this the best way to rewrite the content of a file in Java?
本文介绍了这是用Java重写文件内容的最好方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止我想到的是:
这是最好的方法吗?还是有更直接的方法,就是不必删除和创建文件,而只是简单地改变内容?
解决方案覆盖文件foo.log:
文件myFoo = new File(foo.log);
FileOutputStream fooStream = new FileOutputStream(myFoo,false); //真的追加
// false来覆盖。
byte [] myBytes =New Contents \\\
.getBytes()
fooStream.write(myBytes);
fooStream.close();
或
文件myFoo =新文件(foo.log);
FileWriter fooWriter = new FileWriter(myFoo,false); //真的追加
// false来覆盖。
fooWriter.write(New Contents \\\
);
fooWriter.close();
编辑:显示FileOutputStream和FileWriter的示例...
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?
解决方案
To overwrite file 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
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();
Edit: show examples of both FileOutputStream and FileWriter...
这篇关于这是用Java重写文件内容的最好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文