最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin7浏览0评论

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);
发布评论

评论列表(0)

  1. 暂无评论