首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我需要同时调用.dispose() (javax.jcr.Binary)和.close() (java.io.InputStream)吗?

我需要同时调用.dispose() (javax.jcr.Binary)和.close() (java.io.InputStream)吗?
EN

Stack Overflow用户
提问于 2016-12-16 16:09:59
回答 1查看 227关注 0票数 2

我是否需要分别定义二进制对象,以便在其上调用.dispose(); (参见methodOne()),还是在自动关闭InputStream (参见methodTwo())时会自动处理这些对象?

代码语言:javascript
运行
复制
private void methodOne(Resource resource) {
    Binary binary = resource.getValueMap().get("jcr:data", Binary.class);
    try {
        InputStream is = null;
        try {
            is = binary.getStream();
            // ...do something with the InputStream...
        } catch (RepositoryException e) {
            LOG.error("RepositoryException trying to get an InputStream from the resource.");
        } finally {
            if (is != null) {
                IOUtils.closeQuietly(is);
            }
        }
    } finally {
        binary.dispose();
    }
}

private void methodTwo(Resource resource) {
    try (InputStream is = resource.getValueMap().get("jcr:data", Binary.class).getStream()) {
        // ...do something with the InputStream...
    } catch (IOException e) {
        LOG.error("IOException from trying to auto-close InputStream.");
    } catch (RepositoryException e) {
        LOG.error("RepositoryException trying to get an InputStream from the resource.");
    }
}

我真的很困惑如何测试methodTwo中的匿名二进制资源是否被正确地处理,这就是为什么我一开始就问这个问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-16 16:13:26

除非您从文档中获得的流足够关闭,否则您需要确保列出try中的其他可关闭资源,以使try-with-resources为您关闭它们。

您已经说过Binary不实现AutoCloseable。令人恼火。-)您总是可以定义一个包装器(我认为这不是您需要处理的唯一地方),如下所示:

代码语言:javascript
运行
复制
public class ACBinaryWrapper implements AutoCloseable {
    private Binary binary;

    public ACBinaryWrapper(Binary binary) {
        this.binary = binary;
    }

    public Binary getBinary() {
        return this.binary;
    }

    public void close() { 
        if (this.binary != null) {
            Binary b = this.binary;
            this.binary = null;
            b.dispose();
        }
    }
}

然后:

代码语言:javascript
运行
复制
private void yourMethod(Resource resource) {
    try (
        ACBinaryWrapper acbinary = new ACBinaryWrapper(
            resource.getValueMap().get("jcr:data", Binary.class)
        );
        InputStream is = acbinary.getBinary().getStream();
    ) {
        // ...do something with the InputStream...
    } catch (IOException e) {
        // ...appropriate handling...
    } catch (RepositoryException e) {
        // ...appropriate handling...
    }
}

注意binary是如何与is分开列出的。

您在LOG处理程序中的IOException语句以及类似的语句似乎假定,唯一可能发生的I/O错误是在关闭流时发生的。通常,从流中读取也会导致I/O错误。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41188305

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档