问题
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?
回答1:
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.)
回答2:
It isn't knowable in principle (consider a peer that never stops writing), and you don't need it. Just read and write in a loop using a fixed size buffer. NIO doesn't offer any magical solution.
回答3:
A couple of additional options:
Depending on the blocking nature of the input stream, you could call available() on the stream.
If the streams are smallish, you could write them into PushbackInputStreams, count the bytes and then rewind.
回答4:
you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link
Get Bytes from Inputstream
来源:https://stackoverflow.com/questions/11746978/java-inputstream-size