okw*_*wap 20 java try-with-resources
会隐含地try-with-resources打个电话flush()吗?
如果是,请在以下代码段bw.flush()中安全删除?
static void printToFile1(String text, File file) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(text);
bw.flush();
} catch (IOException ex) {
// handle ex
}
}
Run Code Online (Sandbox Code Playgroud)
PS.我在官方文件中没有看到任何关于它的描述:
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
See*_*ose 14
Closeable并且AutoCloseable是通用接口,不知道有关刷新的任何信息.所以你在他们的文档中找不到任何关于它的信息 - 除了一些关于释放资源的话.
Writer另一方面,A 是一个更具特色的抽象类,现在知道有关刷新的内容.该方法的文档的一些摘录Writer.close():
关闭流,先冲洗它.
所以 - 是的 - 当使用作家时,close总会也会如此flush.这基本上意味着您在查找结束真正做的事情时,必须查阅您正在使用的具体类的文档.
使用try-with-resource块时,资源会自动关闭.作为此过程的一部分,它还将自动调用flush.
正如在BufferedWriter的close方法的doc中所提到的:
关闭流,先冲洗它.关闭流后,进一步的write()或flush()调用将导致抛出IOException.
我真的不明白为什么其他答案集中在BufferedWriternot上try-with-resources。
我也找不到任何规范或提到这些try-with-resources语句flush()调用Flushable.
https://docs.oracle.com/javase/specs/jls/se13/html/jls-14.html#jls-14.20.3
不要依赖供应商特定实现的任何未记录/未指定的行为。
try (OutputStream o = open()) {
//writeSome
o.flush(); // won't hurt!
}
Run Code Online (Sandbox Code Playgroud)