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?
Advertisement
Answer
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.