我遍历预期具有相同行数的文件的行:
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFile)));
BufferedReader[] brs = new BufferedReader[inputFiles.length];
for (int i = 0; i < inputFiles.length; i++) {
brs[i] = Files.newBufferedReader(Paths.get(inputFiles[i]), StandardCharsets.UTF_8);
}
String[] lines = new String[inputFiles.length];
boolean shouldContinue = true;
while (shouldContinue) {
// read all next lines
for (int i = 0; i < inputFiles.length; i++) {
lines[i] = brs[i].readLine();
if (lines[i] == null) {
shouldContinue = false;
}
}
// sanity check
if (!shouldContinue) {
for (String line : lines) {
if (line != null) {
for (int i = 0; i < inputFiles.length; i++) {
brs[i].close();
}
writer.close();
throw new RuntimeException("All files should contain the same number of lines!");
}
}
break;
}
// processing the lines
}
但是,Eclipse Mars对于抛出异常的行收到以下警告:
潜在的资源泄漏:“作者”可能无法在此位置关闭
我做错什么了吗?以及如何解决?
答案 0 :(得分:0)
尝试使用资源
try (BufferedWriter writer = new
BufferedWriter(new FileWriter(new File(outputFile)))){
//code
} catch (Exception e) { // handle exception
}