我的代码正在从web上读取一个HTML页面,我想写出好的代码,所以我想使用try-with-resources或want block来关闭资源。
在下面的代码中,似乎不可能使用它们中的任何一个来结束"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或same来编写相同的代码?
发布于 2013-05-04 08:24:26
我看不出在以下方面有什么特别的困难:
try (BufferedReader in = new BufferedReader(new InputStreamReader(
new URL("myurl").openStream()))) {
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}这不就是你要找的吗?
https://stackoverflow.com/questions/16368974
复制相似问题