似乎有点笨拙。
它是。至少java7尝试使用资源可以解决该问题。
在java7之前,您可以创建一个
closeStream吞咽它的函数:
public void closeStream(Closeable s){ try{ if(s!=null)s.close(); }catch(IOException e){ //Log or rethrow as unchecked (like RuntimException) ;) }}或将try …最终放入try catch中:
try{ BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream())); try{ String inLine; while ((inLine = r.readLine()) != null) { System.out.println(inLine); } }finally{ r.close(); }}catch(IOException e){ e.printStackTrace();}它比较冗长,并且finally中的异常会在try中隐藏一个,但从语义上讲它更接近Java 7中引入的try-with-
resources。



