当你没有显式定义流变量时关闭java中的流?
所以我想知道在Java中这安全吗?
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet(new URI(String)));
XmlPullParser xpp = Util.getXpp(new InputStreamReader(response.getEntity().getContent()));
我没有明确定义 InputStreamReader 这意味着我无法关闭它。不过,我不太喜欢这段代码的外观。我这样做的原因是因为我不想等到解析完 XML 后才关闭流。
一旦代码超出范围,VM 会自动关闭流吗?我是否应该重构我的代码,以便在解析完 XML 后可以显式关闭流?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你需要关闭它。理想情况下,会有一个 try/finally 结构,这样即使出现异常,流也会关闭。 (或者使用新的 Java 7 try-with-resources 东西)
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)
迟到的答案,但以防万一有人仍然想知道这个 try-with-resources 是在 API 19 (4.4) 中为 Android 添加的,所以如果您使用 minSdkVersion 19+,您可以使用它而不是finally 块来自动关闭资源以获得更干净的代码。
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.
大多数软件(嗯,无论如何都是好的软件)遵循这样的原则:创建流的人负责在使用后关闭它。有时您可能会发现一些软件,当提供流时,会在完成流后关闭它,但您不能押注它,这可能不是理想的行为 - 除非有问题的软件做了很多事情在读取流之后但在返回调用者之前工作,在这种情况下,保持流长时间打开可能并不理想。
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.