【问题标题】:Unnecessary resource leak warning in Eclipse for file writerEclipse 中针对文件编写器的不必要的资源泄漏警告
【发布时间】:2019-06-20 18:14:39
【问题描述】:

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

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

潜在的资源泄漏:'writer' 可能不会在此位置关闭

我做错了吗?又该如何解决呢?

【问题讨论】:

  • 如果抛出 IOException,brs[i].close();writer.close(); 可能不会被执行(这称为资源泄漏)。对writer 和每个brs 使用try-with-resources 语句。为此,打开、读取和关闭必须在同一个循环中完成,而不是在三个单独的循环中完成,您必须为此重构代码:writer 的 try-with-resources 包含带有另一个嵌套 try-with 的循环-资源。

标签: java eclipse warnings filewriter


【解决方案1】:

尝试资源

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

【讨论】:

  • 没有帮助。
  • 你正在打开作家和许多读者。您需要关闭所有快乐路径和异常路径,否则警告是合法的。
猜你喜欢
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2016-07-24
  • 2012-10-23
  • 1970-01-01
  • 2021-03-14
相关资源
最近更新 更多