[关闭]
@linux1s1s 2016-02-17T02:50:35.000000Z 字数 1373 阅读 4340

Java中关闭流的正确姿势

2016-02 Java


先看一下信手拈来的流处理代码

  1. public static void fileOperationBad(String path) {
  2. if (!makesureFileExist(path)) {
  3. return;
  4. }
  5. InputStream in = null;
  6. OutputStream os = null;
  7. try {
  8. File f = new File(path);
  9. in = new FileInputStream(f);
  10. os = new FileOutputStream(f);
  11. // ...
  12. in.close();
  13. os.close();
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }

对上面代码,L2中的判断路径文件是否存在这里暂时忽略掉,重点关注L15-L16关闭流的姿势是否正确,这里是典型的初学者最喜欢的代码风格,也是我们极力不推荐的,为什么不推荐,搞不清楚的话可以自行google,那么稍微有点经验的Java程序员对于关闭流的姿势又是什么呢?

  1. public static void fileOperationNormal(String path) {
  2. if (!makesureFileExist(path)) {
  3. return;
  4. }
  5. InputStream in = null;
  6. OutputStream os = null;
  7. try {
  8. File f = new File(path);
  9. in = new FileInputStream(f);
  10. os = new FileOutputStream(f);
  11. // ...
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. } finally {
  15. try {
  16. if (in != null) {
  17. in.close();
  18. }
  19. if (os != null) {
  20. os.close();
  21. }
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }

上面的代码很小心的在finally块中尝试关闭流,但是这样真的能很完整的关闭两个流吗?如果不能很完整的关闭,那么你能指出来原因吗?仔细观察一下不难发现,其实上面代码还是不能完整的关闭流,那么经验丰富的Java程序员该如何做呢?我们来看看下面的代码风格

  1. public static void fileOperationFine(String path) {
  2. if (!makesureFileExist(path)) {
  3. return;
  4. }
  5. InputStream in = null;
  6. OutputStream os = null;
  7. try {
  8. File f = new File(path);
  9. in = new FileInputStream(f);
  10. os = new FileOutputStream(f);
  11. // ...
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. } finally {
  15. closeQuietly(in);
  16. closeQuietly(os);
  17. }
  18. }
  19. private static void closeQuietly(Closeable closeable) {
  20. try {
  21. if (closeable != null) {
  22. closeable.close();
  23. }
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }

上面的代码明显就是经验丰富的程序员应该有的关闭流的正确姿势,原因不再解释。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注