closing nested streams [duplicate]

房东的猫 提交于 2019-11-29 14:29:42
MD Sayem Ahmed

When closing chained streams, you only need to close the outermost stream. Any errors will be propagated up the chain and be caught.

Take a look at here. Probably this question has been asked before.

Always close resources with a finally block:

acquire();
try {
    use();
} finally {
    release();
}

Your only resource here is the FileOutputStream, so it's the only one which really needs to be closed. If the PrintWriter constructor was to throw, you really should release the FileOutputStream anyway, which precludes just closing the PrintWriter.

Note, you really do want to flush the PrintWriter. This only needs to be done in the non-exception case so doesn't need a finally.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!