java – 资源泄漏:’in’从来没有关闭,尽管它已关闭
发布时间:2020-12-14 05:50:09 所属栏目:Java 来源:网络整理
导读:我知道这里有几个类似的题目,但是大多数人都已经忘了在他们的流中放一个close()指令.这是不同的. 让我说我有以下最小的例子: public void test() throws IOException{ InputStream in; if( file.exists() ) { in = new FileInputStream( file ); } else { i
我知道这里有几个类似的题目,但是大多数人都已经忘了在他们的流中放一个close()指令.这是不同的.
让我说我有以下最小的例子: public void test() throws IOException { InputStream in; if( file.exists() ) { in = new FileInputStream( file ); } else { in = new URL( "some url" ).openStream(); } in.close(); } 这给我一个资源泄漏:“in”从来没有在Eclipse中关闭警告(Juno SR1). public void test() throws IOException { InputStream in; if( file.exists() ) { in = new GZIPInputStream( new FileInputStream( file ) ); in.close(); } else { in = new URL( "some URL" ).openStream(); } } 这里发生了什么? 解决方法
这是我如何写:
public void test() throws IOException { InputStream in = null; try { if(file.exists()) { in = new FileInputStream( file ); } else { in = new URL( "some url" ).openStream(); } // Do something useful with the stream. } finally { close(in); } } public static void close(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |