我正在使用 FileWrite 类写入文件。它工作正常。但是 FindBugs 在我的代码 fragment 中指出了一个小问题。
代码 fragment :
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";
FileWriter writer = null;
try {
File root = new File(Environment.getExternalStorageDirectory(), "Test");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, fileName);
writer = new FileWriter(gpxfile, true);
writer.append(text + "\n\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
查找错误报告:
OBL_UNSATISFIED_OBLIGATION:方法可能无法清理流或资源 writeDataToFile(String) 可能无法在检查异常时清理 java.io.Writer
我在哪一行收到此错误?
writer = new FileWriter(gpxfile, true);
谁能简单介绍一下这到底是什么? 我们如何解决这个问题?
最佳答案
您收到此错误是因为 writer.flush();
。这可能会导致 IOException,因为它将任何缓冲输出写入基础流。如果发生异常,编写器将不会关闭。
如果必须在 finally{..}
中刷新,则对每一行使用专用的 try{..} catch{..}
,如下所示:
finally {
if (writer != null) {
try {
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
关于android - writeDataToFile(String) 可能无法在 FindBugs 中检查异常时清理 java.io.Writer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51318841/