开发者社区> 问答> 正文

java – 资源泄漏:’in’从来没有关闭,尽管它已关闭

我知道这里有几个类似的题目,但是大多数人都已经忘了在他们的流中放一个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();
    }
}

这里发生了什么?

展开
收起
游客bnlxddh3fwntw 2020-04-23 21:22:55 782 0
1 条回答
写回答
取消 提交回答
  • 解决方法 这是我如何写:

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

    总结 以上是脚本之家为你收集整理的java – 资源泄漏:’in’从来没有关闭,尽管它已关闭全部内容,希望文章能够帮你解决java – 资源泄漏:’in’从来没有关闭,尽管它已关闭所遇到的程序开发问题。

    2020-04-23 21:23:15
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载