Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to count read bytes from InputStream without allocating the full memory before

Tags:

java

stream

limit

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?

like image 391
Wiesi Avatar asked Aug 02 '26 06:08

Wiesi


1 Answers

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.

like image 51
Fabian Barney Avatar answered Aug 07 '26 19:08

Fabian Barney