在 Java 中交错 BufferedWriter
和 PrintWriter
安全吗?考虑以下示例:
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
来编写文本。但我的问题是:
- 以这种方式使用
PrintWriter
和BufferedWriter
安全吗? - 如果安全,那么没有
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/