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?
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
}
}
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) {
...
}
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.