我知道这里有几个类似的题目,但是大多数人都已经忘了在他们的流中放一个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).
但是当我将in.close()移动到条件块中时,警告消失:
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(); } }