【问题标题】:Interlacing BufferedWriter and PrintWriter隔行扫描 BufferedWriter 和 PrintWriter
【发布时间】:2019-02-10 08:19:18
【问题描述】:

在 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 被访问,因此不回答我的问题。

【问题讨论】:

    标签: java filewriter printwriter bufferedwriter


    【解决方案1】:

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

    正如您在documentation 中看到的:

    一般来说,Writer 会立即将其输出发送到底层 字符或字节流。除非需要立即输出,否则它是 建议在其 write() 的任何 Writer 周围包装一个 BufferedWriter 操作可能成本很高,例如 FileWriters 和 OutputStreamWriters。

    例如:

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

    如果它是安全的,那么没有 bufferedWriter.flush() 是否也是安全的?

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

    再次,来自文档:

    public PrintWriter(OutputStream out)

    创建一个新的 PrintWriter, 没有自动行刷新,来自现有的 OutputStream。这 便利构造函数创建必要的中间体 OutputStreamWriter,它将使用 默认字符编码。

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多