writeDataToFile(String) 可能无法清理 java.io.Writer FindBugs 中的检查异常
writeDataToFile(String) may fail to clean up java.io.Writer on checked exception in FindBugs
我正在使用 FileWrite class 写入一个 file.and 它工作正常。但是 FindBugs 在我的代码片段中指出了一个小问题。
代码片段:
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,因为它将任何缓冲输出写入基础流。如果发生异常,writer 不会被关闭。
如果必须在 finally{..}
中刷新,则对每一行使用专用的 try{..} catch{..}
,如下所示:
finally {
if (writer != null) {
try {
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我正在使用 FileWrite class 写入一个 file.and 它工作正常。但是 FindBugs 在我的代码片段中指出了一个小问题。
代码片段:
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,因为它将任何缓冲输出写入基础流。如果发生异常,writer 不会被关闭。
如果必须在 finally{..}
中刷新,则对每一行使用专用的 try{..} catch{..}
,如下所示:
finally {
if (writer != null) {
try {
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}