Java InputStream Size

I need to get the size in bytes of an InputStream without instantiating a File. Is there a way to do this using Java NIO?

+6
source share
4 answers

From a common InputStream ? You will just need to read and read (for example, in the same buffer, again and again), counting how many bytes you read until you reach the end of the stream.

Of course, you will not be able to read the data yourself ... if you want to do this, you will need to store the data while reading, for example. by copying it to ByteArrayOutputStream .

(If you can process the data at the same time as developing the length, just do it - when you read it with a loop, each time reading it into the same buffer, just increase the counter to record how you read. You did not provide us no information on what you want to do with the stream.)

+24
source

In principle, this is impossible to understand (think of a peer who never stops writing), and you do not need it. Just read and write in a loop using a fixed size buffer. NIO does not offer a magic solution.

+6
source

A couple of additional parameters:

Depending on the nature of the blocking of the input stream, you can call available () on the stream.

If the streams are small, you can write them to PushbackInputStream s, count the bytes and then rewind.

+1
source

you can get the size of InputStream using getBytes (inputStream) Utils.java, check the following link

Get byte from input stream

-2
source

Source: https://habr.com/ru/post/921792/


All Articles