commons-io的FileUtils.readFileToByteArray方法会关闭新创建的流吗?

huangapple go评论102阅读模式
英文:

Does commons-io's FileUtils.readFileToByteArray close the newly created stream?

问题

我正在创建一个为目录中的每个文件生成校验和的程序。我正在使用FileUtils.readFileToByteArray,它在内部创建一个新的FileInputStream。问题是我没有找到在哪里关闭了该流,而且担心可能会出现内存泄漏。

因此我想问:这个方法在读取后会关闭流吗?

英文:

I'm creating a program that produce checksums for each files in directory. I'm using FileUtils.readFileToByteArray which internally creates a new FileInputStream. The problem is I didn't find where the stream is closed and wondering about a possible memory leak.

So I'm asking: does this method close the stream after reading it?

答案1

得分: 1

简短回答:是的,它会关闭流。

稍长的回答:
让我们看一下代码:

try (InputStream in = openInputStream(file)) {
    final long fileLength = file.length();
    // file.length()可能对于依赖系统的实体返回0,将0视为未知长度 - 参见IO-453
    return fileLength > 0 ? IOUtils.toByteArray(in, fileLength) : IOUtils.toByteArray(in);
}

你在这里看到的是 try-with-resource 语法。在 try 的括号中打开的任何 AutoClosable(在这种情况下是 FileInputStream)将在 try 块终止时隐式关闭,无论是正常终止还是通过 return、抛出异常等终止。

英文:

Short answer: yes, it closes the stream.

Slightly longer answer:
Let's look at the code:

try (InputStream in = openInputStream(file)) {
    final long fileLength = file.length();
    // file.length() may return 0 for system-dependent entities, treat 0 as unknown length - see IO-453
    return fileLength > 0 ? IOUtils.toByteArray(in, fileLength) : IOUtils.toByteArray(in);
}

That you see here is the try-with resource syntax. Any AutoClosable opened in the try's parentheses (in this case, a FileInputStream) will be implicitly closed when the try block terminates, whether it terminated normally or by returning, throwing an exception, etc.

huangapple
  • 本文由 发表于 2020年6月5日 22:22:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/62217559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定