java - 交错 BufferedWriter 和 PrintWriter

标签 java filewriter printwriter bufferedwriter

在 Java 中交错 BufferedWriterPrintWriter 安全吗?考虑以下示例:

private void writeToFile(File file, String text, Throwable throwable) throws Exception { // I use the "throws Exception" here for simplicity of the example
    // Write text
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
    bufferedWriter.write(text);
    bufferedWriter.newLine();
    bufferedWriter.flush();

    // Write StackTrace
    PrintWriter printWriter = new PrintWriter(bufferedWriter);
    throwable.printStackTrace(printWriter);
    printWriter.close();
}

我知道我也可以使用 PrintWriter 来编写文本。但我的问题是:

  • 以这种方式使用 PrintWriterBufferedWriter 安全吗?
  • 如果安全,那么没有 bufferedWriter.flush() 也安全吗?
  • 如果安全的话,在使用 PrintWriter 后再次使用 BufferedWriter 是否也安全?

注意类似的问题here假设仅访问 PrintWriter,因此不能回答我的问题。

最佳答案

以这种方式使用 PrintWriter 和 BufferedWriter 安全吗?

正如您在 documentation 中看到的那样:

In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters.

例如:

 PrintWriter out
   = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

如果安全,那么没有 bufferedWriter.flush() 也安全吗?

是的,很安全。 lush()在您调用它时刷新流。恕我直言,根据经验,如果没有自动刷新(并向流写入更大的量),您必须在关闭流之前调用它。

再次,来自文档:

public PrintWriter(OutputStream out)

Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.

所以,如果你使用这个构造函数,你应该在关闭你的流之前调用flush(),如果你使用另一个public PrintWriter(Writer out, boolean autoFlush)并为autoflush定义true,我认为这个调用是不必要的。

如果安全的话,在使用 PrintWriter 之后再次使用 BufferedWriter 是否也安全?

如果您为追加定义了FileWriter,那将是安全的。现在,您将在每次调用函数时覆盖您的文件。 所以我会使用这个构造函数:FileWriter(File file, boolean append) 并为追加指定 true。

什么不安全:您应该使用带有 autoflush 或 try-catch-finally 的 try-with-resources 语句,并关闭(也许刷新)您的流,以便正确释放资源。

关于java - 交错 BufferedWriter 和 PrintWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52180853/

相关文章:

java - 将 PrinterWriter 与字符串 ArrayList 结合使用

java - 将随机数组输出到文件

java - 无序 XSD 序列的标准解决方案

java - 无法连接到 SOCKS 代理 :Connection refused: connect

java - 设计类的问题

java - 使用输入字符串 "exit"在终端中退出程序

java - 在递归计算幂时我不理解我的方法的输出

java - 为什么 FileWriter 有 write(String) 却没有 FileReader.read(String)

java - Java 中的斐波那契数列使用动态编程和递归

Java PrintWriter 错误