Eclipse中针对文件编写器的不必要的资源泄漏警告

时间:2019-01-27 16:19:34

标签: java eclipse warnings filewriter

我遍历预期具有相同行数的文件的行:

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对于抛出异常的行收到以下警告:

  

潜在的资源泄漏:“作者”可能无法在此位置关闭

我做错什么了吗?以及如何解决?

1 个答案:

答案 0 :(得分:0)

尝试使用资源

 try (BufferedWriter writer = new 
      BufferedWriter(new FileWriter(new File(outputFile)))){
        //code
 } catch (Exception e) { // handle exception
 }