Java io ugly try-finally block

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

    One trick I sometimes use is to define a method called closeQuietly(Closeable) that tests to see if its argument is null then closes it, ignoring any exceptions. But you need to be a careful closing OutputStreams and Writers that way because they may actually throw an exception that matters; e.g. if the final flush fails.

    Things are likely to improve with Java 7. Reports are that it will have a new construct that provides a more concise way of handling managed resources; e.g. streams that need to be closed when they are finished with.

    Finally, you should be aware that your example has a bug. If the method call to open the second stream, the first stream will not be closed. The second open needs to be done inside the try block.

提交回复
热议问题