Closing inputstreams in Java

前端 未结 6 1084
眼角桃花
眼角桃花 2020-12-03 13:19

I have the following piece of code in a try/catch block

 InputStream inputstream = conn.getInputStream();
 InputStreamReader inputstreamreader = new  InputSt         


        
6条回答
  •  清歌不尽
    2020-12-03 14:15

    You only need to close the actual resource. You should close the resource even if constructing decorators fails. For output, you should flush the most decorator object in the happy case.

    Some complications:

    • Sometimes the decorators are different resources (some compression implementations use the C heap).
    • Closing decorators in sad cases actually causes flushes, with ensuing confusion such as not actually closing the underlying resource.
    • It looks like you underlying resource is a URLConnection, which doesn't have a disconnect/close method as such.

    You may wish to consider using the Execute Around idiom so you don't have to duplicate this sort of thing.

提交回复
热议问题