Convert InputStream to byte array in Java

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

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

30条回答
  •  花落未央
    2020-11-21 12:40

    You can use Apache Commons IO to handle this and similar tasks.

    The IOUtils type has a static method to read an InputStream and return a byte[].

    InputStream is;
    byte[] bytes = IOUtils.toByteArray(is);
    

    Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray(). It handles large files by copying the bytes in blocks of 4KiB.

提交回复
热议问题