在我的真實項目中重現問題的簡短方法。環境:Android SDK 1.16,Eclipse 4.2.0,Windows。在Save1
功能fos = new FileOutputStream(file)
資源泄漏:流從未關閉
private void Save1(boolean externalStorage)
{
String s = "12345";
File file;
FileOutputStream fos = null;
if (externalStorage)
{
try
{
file = new File(getExternalFilesDir(null), "log");
fos = new FileOutputStream(file); // Resource leak: 'fos' is never closed
}
catch(FileNotFoundException e)
{
return;
}
}
else
{
try
{
fos = openFileOutput("log", Context.MODE_PRIVATE);
}
catch(FileNotFoundException e)
{
return;
}
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
return;
}
}
private void Save2(boolean externalStorage)
{
String s = "12345";
File file;
FileOutputStream fos = null;
try
{
file = new File(getExternalFilesDir(null), "log");
fos = new FileOutputStream(file); // OK
}
catch(FileNotFoundException e)
{
return;
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
return;
}
}
線,警告:創建默認的Android應用程序,將下面的代碼添加到MainActivity.java Resource leak: 'fos' is never closed
的同一線上Save2
功能:無需警告。
請不要發送未經測試的答案,問題並不像看起來那麼簡單。將fos.close()
添加到該函數的不同部分並沒有幫助。
哇。編譯器錯誤?當fos未關閉時,我看不到任何可能的路徑。有興趣地觀看.... – Simon
@Simon:如果這是編譯器錯誤,我不在乎 - 我可以編寫兩個不同的函數。我只是想知道這是否是我的錯誤。 –
其實,更像是一個Lint bug,但我正在檢查它。 – Simon