Closing streams in java when you don't explicitly define the stream variable?

試著忘記壹切 提交于 2019-12-24 10:13:20

问题


So I'm wondering in Java is this safe?

HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet(new URI(String)));
XmlPullParser xpp = Util.getXpp(new InputStreamReader(response.getEntity().getContent()));

I'm not explicitly defining the InputStreamReader which means there's no way for me to close it. I don't particularly like the look of this code, though. The reason I'm doing it this way is because I don't want to have to wait to close the stream until after I'm done the parsing the XML.

Will the VM automatically close the stream once the code is out of scope? Should I refactor my code so I can explicitly close the stream once I'm done parsing the XML?


回答1:


You need to close it. Ideally, there would be a try / finally structure so that even if there is an Exception the stream gets closed. (Or use new Java 7 try-with-resources stuff)

InputStreamReader reader = null;
try {
   all the stuff that might fail (IOException etc...)
}
finally {
  if (reader != null)
    try {
       reader.close();
    }
    catch (IOExcetpion ioe) {
       ; // this is one of the very few cases it's best to ignore the exception
    }
}



回答2:


Late answer but in case anyone is still wondering about this try-with-resources was added for Android in API 19 (4.4) so if you're using minSdkVersion 19+ you can use it instead of finally blocks for auto closable resources for cleaner code.

    ...
    try (InputStreamReader reader = new InputStreamReader(response.getEntity().getContent())) {
        ...
    } catch (IOException e) {
        ...
    }



回答3:


Most software (well, good software anyway) follows the principle that whoever creates a stream is responsible for closing it after use. You might sometimes find software which, when supplied with a stream, closes it when it has finished with it, but you can't bet on it and it's probably not desirable behaviour - except perhaps in cases where the software in question does a lot of work after reading the stream but before returning to the caller, where keeping the stream open for an extended period of time might not be desirable.



来源:https://stackoverflow.com/questions/8863890/closing-streams-in-java-when-you-dont-explicitly-define-the-stream-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!