Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java InputStream size

I need to get the size in bytes of an InputStream without creating a File instance. Is there any way to do it using Java NIO?

like image 229
user1566669 Avatar asked Jul 31 '12 18:07

user1566669


People also ask

Is InputStream in memory?

– Daniel B. And that is because InputStream itself doesn't hold anything in memory. Note that InputStream is an abstract class and exact details depend on the specific subclass.


1 Answers

Of a general InputStream? You'd have to just keep reading and reading (e.g. into the same buffer, over and over) counting how many bytes you've read, until you come to the end of the stream.

Of course, you then won't be able to read the data itself... if you want to do that, you'll need to keep the data as you read it, e.g. by copying it to a ByteArrayOutputStream.

(If you're able to process the data at the same time as working out the length, just do that - as you read it using a loop, reading into the same buffer each time, just increment a counter to record how much you've read. You haven't really provided us any information about what you want to do with the stream.)

like image 87
Jon Skeet Avatar answered Nov 10 '22 07:11

Jon Skeet