2
我是否需要單獨定義Binary對象,以便我可以調用.dispose();
(請參閱methodOne()
),或者在自動關閉InputStream時自動處理它(請參閱methodTwo()
)?我是否需要調用.dispose()(javax.jcr.Binary)和.close()(java.io.InputStream)?
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匿名二進制資源正在被妥善處置,這就是爲什麼我甚至要求在第一時間這個問題,甚至測試真正困惑。
非常感謝您對IOException處理的澄清以及快速回答! javax.jcr.Binary不擴展Closeable或AutoCloseable,因此在try-with-resources聲明中聲明它不一定會處理對'.dispose();'的調用,對吧? – Gdubz
@gdubz:對不起,我的錯誤,我認爲它是'AutoCloseable'。一秒鐘...... –
這很好。讀取類中的註釋,聽起來像我負責調用InputStream上的'.close()'和Binary對象上的'.dispose()'。我只是不清楚調用'.getStream()'關閉鏈式初始化(我猜將一個匿名Binary對象留在那裏?),或者甚至如何測試/調試它。 – Gdubz