java 创建并写入文件内容,这是在Java中创建文件并写入文件的最佳方法

I normally use PrintWritter object to create and write to a file, but not sure if its the best in terms of speed and security compare to other ways of creating and writing to a file using other approaches i.e.

Writer writer = new BufferedWriter(

new OutputStreamWriter(

new FileOutputStream("example.html"), "utf-8"));

writer.write("Something");

vs

File file = new File("example.html");

BufferedWriter output = new BufferedWriter(new FileWriter(file));

output.write("Something");

vs

File file = new File("example.html");

FileOutputStream is = new FileOutputStream(file);

OutputStreamWriter osw = new OutputStreamWriter(is);

Writer w = new BufferedWriter(osw);

w.write("something");

vs

PrintWritter pw = new PrintWriter("example.html", "UTF-8");

pw.write("Something");

Also, when to use one over the other; a use case scenario would be appreciated. I'm not asking for how to create and write to file, I know how to do that. Its more of compare and contrast sort of question I'm asking.

解决方案

I prefer:

boolean append = true;

boolean autoFlush = true;

String charset = "UTF-8";

String filePath = "C:/foo.txt";

File file = new File(filePath);

if(!file.exists()) file.mkdirs();

FileOutputStream fos = new FileOutputStream(file, append);

OutputStreamWriter osw = new OutputStreamWriter(fos, charset);

BufferedWriter bw = new BufferedWriter(osw);

PrintWriter pw = new PrintWriter(bw, autoFlush);

pw.write("Some File Contents");

which gives you:

Decide whether to append to the text file or overwrite it.

Decide whether to make it auto-flush or not.

Specify the charset.

Make it buffered, which improves the streaming performance.

Convenient methods (such as println() and its overloaded ones).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值