Java InputStream size

后端 未结 4 1639
醉酒成梦
醉酒成梦 2020-12-19 06:03

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?

4条回答
  •  死守一世寂寞
    2020-12-19 06:34

    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.)

提交回复
热议问题