Eclipse(Juno)发出以下警告:
潜在资源泄漏:"os"可能未关闭
在该代码中try
主体的第一行:
static void saveDetails(byte[] detailsData) {
OutputStream os = null;
try {
os = sContext.openFileOutput(DETAILS_FILE_NAME, Context.MODE_PRIVATE);
os.write(detailsData);
} catch (IOException e) {
Log.w(LOG_TAG, "Unable to save details", e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ignored) {
}
}
}
}
方法openFileOutput
被声明为抛出一个FileNotFoundException
。
这是假阳性吗?这似乎是一个相当普通的执行路径分析。
在我看来,这是一个假阳性。您的资源在一个"finally"块中关闭,所以我看不出这里可能出了什么问题。
顺便说一句,如果您正在使用Java7,我建议您使用"尝试使用资源"的习惯用法。
static void saveDetails(byte[] detailsData) {
try (OutputStream os = sContext.openFileOutput(DETAILS_FILE_NAME, Context.MODE_PRIVATE);) {
os = sContext.openFileOutput(DETAILS_FILE_NAME, Context.MODE_PRIVATE);
os.write(detailsData);
} catch (IOException e) {
Log.w(LOG_TAG, "Unable to save details", e);
}
}
如果将open和close都移到first-try子句会怎样?它们抛出相同类型的异常。并删除if os!=无效的
我猜这是因为在关闭之前有if (os != null)
。由于它是有条件的,所以OutputStream可能没有关闭。
如果你尝试会发生什么:
static void saveDetails(byte[] detailsData) {
OutputStream os = null;
try {
os = sContext.openFileOutput(DETAILS_FILE_NAME, Context.MODE_PRIVATE);
os.write(detailsData);
} catch (IOException e) {
Log.w(LOG_TAG, "Unable to save details", e);
} finally {
try {
os.close();
} catch (IOException ignored) {
}
}
}