【发布时间】:2017-10-30 16:02:10
【问题描述】:
在 Android 中使用 Java 的 try with resources 是否安全 - 它是否检查可关闭对象是否不为空,是否在尝试关闭它时捕获 close 抛出的异常?
如果我转换这个:
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
}
到
try (FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel()) {
inChannel.transferTo(0, inChannel.size(), outChannel);
}
它会在尝试调用close 之前检查inChannel 和outChannel 是否不为空吗?
另外,在这里使用 try 与资源是否安全:
try {
cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media.DATA},
MediaStore.Images.Media._ID + " =? ",
new String[]{"" + imageIdInMediaStore},
null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
return cursor.getString(0);
} else {
return "";
}
} catch (Exception e) {
return "";
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
cursor = null;
}
}
finally 块对 !cursor.isClosed() 进行了重要检查 - try with resources 会弄清楚如何做到这一点,还是我应该保持不变?
【问题讨论】:
-
为什么说
cursor.isClosed()是“重要的检查”?只需致电cursor.close()。close()方法要求是幂等的,所以isClosed()调用是多余的。在已经关闭的cursor上调用close()没有任何作用。正如javadoc 所说:如果流已关闭,则调用此方法无效。 -
为什么它们会为空?他们怎么可能是空的?