这是在Java中创建文件并写入文件的最佳方法 [英] Which is the best way to create file and write to it in Java

查看:1637
本文介绍了这是在Java中创建文件并写入文件的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常使用 PrintWritter 对象来创建和写入文件,但不确定它在速度和安全性方面是否与其他创建和编写方式相比最佳使用其他方法的文件,即

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



vs

File file = new File("example.html");
BufferedWriter output = new BufferedWriter(new FileWriter(file));          
output.write("Something");



vs



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



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.

推荐答案

我更喜欢:

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");

给你:


  1. 决定是否附加到文本文件或覆盖它。

  2. 决定是否自动刷新。

  3. 指定字符集。

  4. 使其缓冲,从而提高流媒体性能。

  5. 方便的方法(例如 println() 及其超载的)。

  1. Decide whether to append to the text file or overwrite it.
  2. Decide whether to make it auto-flush or not.
  3. Specify the charset.
  4. Make it buffered, which improves the streaming performance.
  5. Convenient methods (such as println() and its overloaded ones).

这篇关于这是在Java中创建文件并写入文件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆