我写了一小段打印代码:
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(FileDescriptor.out), "ASCII"), 512);
out.write(msg + '\n');
out.flush();
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(
"Test failed ",
e);
} catch (IOException e) {
throw new IllegalStateException(
"Test failed", e);
} finally {
if (out != null) {
out = null;
}
}
obj 的刷新仅在 try block 中完成。那么这是一个好方法还是我应该刷新 finally block 中的对象?
最佳答案
如果可以,请使用现代语法,不要担心所有这些。关闭会自动刷新它,所以只需使用 try-with-resources 语法。此代码更短且更易读:
try(BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(FileDescriptor.out), "ASCII"), 512)) {
out.write(msg + '\n');
} catch (UnsupportedEncodingException | IOException e) {
logger.info("Test failed due to exception.");
throw new IllegalStateException("Test failed", e);
}
查看更多关于 try-with-resources 的信息如果您不熟悉语法。
关于java - 冲洗物体的正确位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30260570/