在我的真实项目中重现问题的简短方法。环境: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