这是在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).