I'm planning to use readAllBytes()
on a DigestInputStream
to do checksum calculation. I'm worried about the case the input file is too big and, as specified on Java documentation, an OutOfMemoryError
exception is thrown in that case. However, I'm not sure what would happen if the return value (byte[]
) is ignored. That is, after this initialization:
DigestInputStream d=new DigestInputStream(new FileInputStream("example.txt"), MessageDigest.getInstance("SHA-1")) ;
Doing this:
d.readAllBytes();
Instead of:
byte[] a=d.readAllBytes();
My question is: would OutOfMemoryError
exception be thrown or not in the former case, considering that's not apparently necessary to allocate a byte[]
if I ignore the return value of readAllBytes()
method?
I'm planning to use readAllBytes()
on a DigestInputStream
to do checksum calculation. I'm worried about the case the input file is too big and, as specified on Java documentation, an OutOfMemoryError
exception is thrown in that case. However, I'm not sure what would happen if the return value (byte[]
) is ignored. That is, after this initialization:
DigestInputStream d=new DigestInputStream(new FileInputStream("example.txt"), MessageDigest.getInstance("SHA-1")) ;
Doing this:
d.readAllBytes();
Instead of:
byte[] a=d.readAllBytes();
My question is: would OutOfMemoryError
exception be thrown or not in the former case, considering that's not apparently necessary to allocate a byte[]
if I ignore the return value of readAllBytes()
method?
- 3 "considering that's not apparently necessary to allocate a byte[] if I ignore the return value of readAllBytes() method" - where do you get the impression that it's "not apparently necessary"? – Jon Skeet Commented Mar 20 at 21:15
1 Answer
Reset to default 6Discarding the return value of readAllBytes
will not prevent an OutOfMemoryError
from being thrown. In the implementation of readAllBytes
, a byte[]
large enough to store all the bytes has to be allocated at some point, and this is where an OutOfMemoryError
would potentially be thrown. The code that allocates this byte[]
will still be run even if you discard the return value - after all, readAllBytes
has no way of knowing whether you will discard the return value or not.
If you don't care about the bytes read and just want the digest, you can create a fixed sized buffer and repeatedly read into it until the end of the stream, e.g.
byte[] buffer = new byte[2048];
while (digestInputStream.read(buffer) >= 0);