在java中关闭流时,你并没有明确定义流变量? [英] Closing streams in java when you don't explicitly define the stream variable?

查看:394
本文介绍了在java中关闭流时,你并没有明确定义流变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在Java中不知道是这安全吗?

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()));

我没有明确定义,这意味着有没有办法对我来说,关闭它的InputStreamReader。我并不特别喜欢这个code的外观,虽然。这样一来,我做的原因是因为我不希望有等待关闭流,直到我做了解析XML了。

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.

请问VM自动关闭该流一旦code是超出范围?我应该修改我的code,所以我可以明确地关闭该流一旦我做了解析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?

推荐答案

您需要关闭它。理想情况下,会有一个try /终于结构,这样即使有异常数据流被关闭。 (或者使用新的Java 7的try-与资源的东西)

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
    }
}

这篇关于在java中关闭流时,你并没有明确定义流变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆