为什么此代码会生成“潜在资源泄漏”警告?

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”块中关闭,因此我无法看到这里可能出现的问题。

作为旁注,如果您使用的是Java 7,我建议使用“try-with-resources”习惯用法。

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

如果你同时打开和关闭第一个试试条款怎么办? 他们抛出相同类型的exception。 并删除if os!= null。

我的猜测是因为你在关闭前有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) { } } }