Java:如何计算从InputStream读取的字节数而不先分配完整的内存 [英] Java: How to count read bytes from InputStream without allocating the full memory before
问题描述
我有一个Java后端,用户可以在其中上传文件.我想将这些上传的文件限制为最大大小,并希望在上传发生时检查上传的字节数,并在达到限制后立即中断传输.
当前,我在分配之前使用InputStream.available()来确定估计的大小,但这似乎不可靠.
有什么建议吗?
您可以使用 Apache IO的CountingInputStream .
另一方面,当您要在达到某个限制时立即停止上载时,只需在读取字节块时计数并在超出限制时关闭流即可.
I have a Java-backend where user can upload files to it. I want to limit these uploaded files to a max size and want to check the amount of uploaded bytes while the upload happens and break the transmission as soon as the limit is reached.
Currently I am using InputStream.available() before allocation for determination of estimated size, but that seems to be seen as unreliable.
Any suggestions?
You can use Guava's CountingInputstream or Apache IO's CountingInputStream when you want to know how many bytes have been read.
On the other hand when you want to stop the upload immediatly when reaching some limit then just count while reading chunks of bytes and close the stream when the limit has been exceeded.
这篇关于Java:如何计算从InputStream读取的字节数而不先分配完整的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!