英文:
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 return
ing, throwing an exception, etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论