我是否需要分别定义二进制对象,以便在其上调用.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.");
}
}
我真的很困惑如何测试methodTwo中的匿名二进制资源是否被正确地处理,这就是为什么我一开始就问这个问题。
发布于 2016-12-16 16:13:26
除非您从文档中获得的流足够关闭,否则您需要确保列出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...
}
}
注意binary
是如何与is
分开列出的。
您在LOG
处理程序中的IOException
语句以及类似的语句似乎假定,唯一可能发生的I/O错误是在关闭流时发生的。通常,从流中读取也会导致I/O错误。
https://stackoverflow.com/questions/41188305
复制相似问题