InputStream关闭和声纳问题

问题描述 投票:1回答:2

我有以下代码打开包含多个文件的zip文件,并从每个文件中提取信息:

public static void unzipFile(InputStream zippedFile) throws IOException {
  try (ZipInputStream zipInputStream = new ZipInputStream(zippedFile)) {
    for (ZipEntry zipEntry = zipInputStream.getNextEntry(); zipEntry != null; zipEntry = zipInputStream.getNextEntry()) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(new BoundedInputStream(zipInputStream, 1024)));
      //Extract info procedure...
    } 
  }
}

总之,我从zip中选择每个文件,然后用BufferedReader打开它以从中读取信息。我也使用BoundedInputStreamorg.apache.commons.io.input.BoundedInputStream)来限制缓冲区大小并避免文件中不需要的大线。

它按预期工作,但我在Sonar上收到此警告:

Use try-with-resources or close this "BufferedReader" in a "finally" clause.

我只是无法关闭(或使用try-with-resources,就像我在方法开头所做的那样)我创建的BufferedReaders - 如果我调用close方法,ZipInputStream将关闭。 ZipInputStream已经在尝试资源......

这个声纳通知被标记为关键,但我认为这是误报。我想知道你是否可以向我澄清 - 我是否正确,还是应该以不同的方式解决这个问题?我不想在代码中留下资源泄漏,因为这种方法将被多次调用,泄漏可能会造成严重损害。

java sonarqube bufferedreader file-handling zipfile
2个回答
1
投票

声纳通知是正确的,因为技术上存在资源泄漏,随着时间的推移会耗尽资源(参见garbage collection and IO classes)。为了避免关闭潜在的ZipInputStream,考虑将ZipEntry传递到for循环中的BoundedInputStream,根据这个问题:reading files in a zip file。因此,当BufferedReader关闭时,BoundedInputStream关闭而不是ZipInputStream


1
投票

感谢这里的答案,我可以这样解决我的问题:

BoundedInputStream boundedInputStream = new BoundedInputStream(zipInputStream, MAX_LINE_SIZE_BYTES);
boundedInputStream.setPropagateClose(false);

try(BufferedReader reader = new BufferedReader(new InputStreamReader(boundedInputStream))) { ...

使用boundedInputStream.setPropagateClose(false);,我可以在不关闭zipInputStream的情况下关闭BufferedReader

© www.soinside.com 2019 - 2024. All rights reserved.