Java io ugly try-finally block

前端 未结 12 1123
爱一瞬间的悲伤
爱一瞬间的悲伤 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:57

    This is the correct idom (and it works fine):

       InputStream in = null;
       OutputStream out = null;
       try {
           in = new FileInputStream(inputFileName);
           out = new FileOutputStream(outputFileName);
           copy(in, out);
       finally {
           close(in);
           close(out);
       }
    
      public static void close(Closeable c) {
         if (c == null) return; 
         try {
             c.close();
         } catch (IOException e) {
             //log the exception
         }
      }
    

    The reason this works fine is that the exception thrown before you got to finally will be thrown after your finally code finishes, provided that your finally code doesn't itself throw an exception or otherwise terminate abnormally.

    Edit: As of Java 7 (and Android SDK 19 - KitKat) there is now a Try with resources syntax to make this cleaner. How to deal with that is addressed in this question.

提交回复
热议问题