Convert InputStream to byte array in Java

前端 未结 30 3501
無奈伤痛
無奈伤痛 2020-11-21 12:08

How do I read an entire InputStream into a byte array?

30条回答
  •  醉话见心
    2020-11-21 12:59

    Finally, after twenty years, there’s a simple solution without the need for a 3rd party library, thanks to Java 9:

    InputStream is;
    …
    byte[] array = is.readAllBytes();
    

    Note also the convenience methods readNBytes(byte[] b, int off, int len) and transferTo(OutputStream) addressing recurring needs.

提交回复
热议问题