[英]Does commons-io's FileUtils.readFileToByteArray close the newly created stream?
I'm creating a program that produce checksums for each files in directory.我正在创建一个程序,为目录中的每个文件生成校验和。 I'm using
FileUtils.readFileToByteArray
which internally creates a new FileInputStream.我正在使用
FileUtils.readFileToByteArray
,它在内部创建一个新的 FileInputStream。 The problem is I didn't find where the stream is closed and wondering about a possible memory leak.问题是我没有找到 stream 的关闭位置,并且想知道可能的 memory 泄漏。
So I'm asking: does this method close the stream after reading it?所以我要问:这个方法读完stream会关闭吗?
Short answer: yes, it closes the stream.简短回答:是的,它关闭了 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.您在此处看到的是try-with 资源语法。 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.在
try
的括号中打开的任何AutoClosable
(在本例中为FileInputStream
)都将在try
块终止时隐式关闭,无论它是正常终止还是通过return
ing、抛出异常等方式终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.