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

时间:2016-12-16 16:09:59

标签: java aem sling

我是否需要单独定义二进制对象,以便我可以在其上调用.dispose();(请参阅methodOne())或自动关闭InputStream时自动处理(请参阅methodTwo() )?

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.");
    }
}

我真的很困惑如何测试方法二中的匿名二进制资源是否被正确处理,这就是为什么我甚至首先要问这个问题。

1 个答案:

答案 0 :(得分:4)

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

您说过Binary没有实现AutoCloseable。刺激。 :-)你总是可以定义一个包装器(因为我认为这不是你需要处理的唯一地方),这些内容如下:

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

然后:

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...
    }
}

请注意binaryis分开列出的方式。

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