2013-05-03 63 views
-1

我的代碼正在從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或者最後寫出相同的代碼嗎?

+0

無關的問題:爲什麼要將'IOException'轉換爲'RuntimeException'? – dlev 2013-05-03 23:30:20

+1

如果您將其更改爲RuntimeException,請確保包含原始異常:'throw new RuntimeException(e);' – nullptr 2013-05-03 23:35:47

+0

哦,是的,我忘了。我更新了它。 – user1883212 2013-05-03 23:58:35

回答

1
BufferedReader in = null; 
try { 

    URL url = new URL("myurl"); 
      in = new BufferedReader(
      new InputStreamReader(
      url.openStream())); 

    String line = ""; 

    while((line = in.readLine()) != null) { 
     System.out.println(line); 
    } 


} catch (IOException e) { 
    throw new RuntimeException(); 
} finally { 
    try { 
     in.close(); 
    } catch (Exception ex) { 
     // This exception is probably safe to ignore, 
     // we are just making a best effort to close the stream. 
    } 
} 

具有在最後塊結束時背後的想法是,如果一些例外在tryio.close()之前發射,流將仍然被封閉。有時候不知道finally的人會關閉每個catch塊中的流,這很醜陋。

+0

這個解決方案並不像看起來那麼簡單,因爲這個代碼是我想要的,但不幸的是它不能編譯。 – user1883212 2013-05-03 23:37:25

+0

1)您是否在'try'塊之外移動了'in'聲明? 2)如果我不知道它是什麼,我怎樣才能幫你編譯錯誤? – 2013-05-03 23:38:46

+0

是的,我也嘗試在我的Eclipse中複製你的代碼。它要求用另一個try-catch包圍in.close – user1883212 2013-05-03 23:42:05

1

我看不出有以下任何特別的困難:

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

難道不是你想要的?

+0

是的,這就是我想要做的 – user1883212 2013-05-04 22:28:29