2013-05-03 61 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