我的代码正在从Web上读取一个HTML页面,我想编写好的代码,所以我想使用try-with-resources或finally块关闭资源。不能使用try-with-resources或者最终阻止
下面的代码似乎不可能使用它们中的任何一个关闭“in”。
try {
URL url = new URL("myurl");
BufferedReader in = new BufferedReader(
new InputStreamReader(
url.openStream()));
String line = "";
while((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (IOException e) {
throw new RuntimeException(e);
}
你能用try-with-resources或者最后写出相同的代码吗?
无关的问题:为什么要将'IOException'转换为'RuntimeException'? – dlev 2013-05-03 23:30:20
如果您将其更改为RuntimeException,请确保包含原始异常:'throw new RuntimeException(e);' – nullptr 2013-05-03 23:35:47
哦,是的,我忘了。我更新了它。 – user1883212 2013-05-03 23:58:35