Java io ugly try-finally block

前端 未结 12 1084
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 05:57

Is there a not so ugly way of treat the close() exception to close both streams then:

    InputStream in = new FileInputStream(inputFileName);
          


        
12条回答
  •  感情败类
    2020-11-28 06:51

    You could implement a utility method:

    public final class IOUtil {
      private IOUtil() {}
    
      public static void closeQuietly(Closeable... closeables) {
        for (Closeable c : closeables) {
            if (c != null) try {
              c.close();
            } catch(Exception ex) {}
        }
      }
    }
    

    Then your code would be reduced to:

    try {
      copy(in, out);
    } finally {
      IOUtil.closeQuietly(in, out);
    }
    

    Additional

    I imagine there'll be a method like this in a 3rd party open-source library. However, my preference is to avoid unnecessary library dependencies unless I'm using a large portion of its functionality. Hence I tend to implement simple utility methods like this myself.

提交回复
热议问题