private void SaveLog(boolean externalStorage)
{
String s = tv_log.getText().toString();
File file;
FileOutputStream fos;
if ( externalStorage )
{
try
{
file = new File(getExternalFilesDir(null), FILE_LOG);
fos = new FileOutputStream(file); // Warning: Resource leak: 'fos' is never closed
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
else
{
try
{
fos = openFileOutput(FILE_LOG, Context.MODE_PRIVATE);
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
为什么警告显示在行中fos = new FileOutputStream(file)
?有趣的是,如果我删除if ( externalStorage )
并只留下第一个分支,则不会显示警告:
private void SaveLog(boolean externalStorage)
{
String s = tv_log.getText().toString();
File file;
FileOutputStream fos;
try
{
file = new File(getExternalFilesDir(null), FILE_LOG);
fos = new FileOutputStream(file); // OK!
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}