Java:如何计算从InputStream读取的字节数而不先分配完整的内存 [英] Java: How to count read bytes from InputStream without allocating the full memory before

查看:755
本文介绍了Java:如何计算从InputStream读取的字节数而不先分配完整的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java后端,用户可以在其中上传文件.我想将这些上传的文件限制为最大大小,并希望在上传发生时检查上传的字节数,并在达到限制后立即中断传输.

当前,我在分配之前使用InputStream.available()来确定估计的大小,但这似乎不可靠.

有什么建议吗?

解决方案

您可以使用 解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆