How do I read an entire InputStream
into a byte array?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
As always, also Spring framework (spring-core since 3.2.2) has something for you:
StreamUtils.copyToByteArray()
See the
InputStream.available()
documentation:You can use Apache Commons IO to handle this and similar tasks.
The
IOUtils
type has a static method to read anInputStream
and return abyte[]
.Internally this creates a
ByteArrayOutputStream
and copies the bytes to the output, then callstoByteArray()
. It handles large files by copying the bytes in blocks of 4KiB.You need to read each byte from your
InputStream
and write it to aByteArrayOutputStream
. You can then retrieve the underlying byte array by callingtoByteArray()
; e.g.I use this.
Here is an optimized version, that tries to avoid copying data bytes as much as possible: