我的代碼正在從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