java - Memory allocation problem on method readAllBytes of DigestInputStream class - Stack Overflow

I'm planning to use readAllBytes() on a DigestInputStream to do checksum calculation. I'm wor

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?

Share Improve this question asked Mar 20 at 21:13 PestroPestro 737 bronze badges 1
  • 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
Add a comment  | 

1 Answer 1

Reset to default 6

Discarding 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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744383945a4571570.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信