Short way to reproduce the problem in my real project. Environment: Android SDK 1.16, Eclipse 4.2.0, Windows. Create default Android application and add the following code to 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;
}
}
Line fos = new FileOutputStream(file) in Save1 function, warning: Resource leak: 'fos' is never closed
The same line in Save2 function: no warnings.
Please don’t send untested answers, the problem is not so simple as it looks. Adding fos.close() to different parts of the function doesn’t help.
It also go away if i add an finally block to the try in the if block like this:
It is getting interesting…
So my guess would be, So if you are opening an Stream in a try block and catch block has an return statement then there should be a finally block that close the stream.
Something like that..
A tried the same code in a simple java project in eclipse and still got the warning. So it looks like is not related to lint or android. It looks like the eclipse compiler issue. Following is the code, I had to create a dummy openFileOutput() method since it is not available n java: