在我的真实项目中重现问题的捷径。环境:Android SDK 1.16、Eclipse 4.2.0、Windows。创建默认 Android 应用程序并将以下代码添加到 MainActivity.java:
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;
}
}
行进功能fos = new FileOutputStream(file)
,Save1
警告:Resource leak: 'fos' is never closed
函数中的同一行Save2
:没有警告。
请不要发送未经测试的答案,问题并不像看起来那么简单。添加fos.close()
到函数的不同部分并没有帮助。