Do I need to close InputStream after I close the Reader

前端 未结 5 984
面向向阳花
面向向阳花 2020-12-05 16:50

I was wondering, whether is there any need for me to close the InputStream, after I close the reader?

    try {
        inputStream = new java.io.FileInputSt         


        
5条回答
  •  伪装坚强ぢ
    2020-12-05 17:36

    Technically, closing the Reader will close the InputStream. However, if there was a failure between opening the InputStream and creating the Reader, you should still close the InputStream. If you close the InputStream [the resource] there shouldn't be a good reason to close the Reader [the decorator]. There are also popular bugs where closing a decorator can throw an exception before closing the decorated. So:

    Resource resource = acquire();
    try {
        Decorator decorated = decorate(resource);
        use(decorated);
    } finally {
        resource.release();
    }
    

    There are some complications to watch out for. Some decorators may actually contain native resources due to their implementation. Output decorators will generally need to be flushed, but only in the happy case (so in the try not the finally block).

提交回复
热议问题