Convert InputStream to byte array in Java

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

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

30条回答
  •  梦谈多话
    2020-11-21 12:43

    You need to read each byte from your InputStream and write it to a ByteArrayOutputStream.

    You can then retrieve the underlying byte array by calling toByteArray():

    InputStream is = ...
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    
    int nRead;
    byte[] data = new byte[16384];
    
    while ((nRead = is.read(data, 0, data.length)) != -1) {
      buffer.write(data, 0, nRead);
    }
    
    return buffer.toByteArray();
    

提交回复
热议问题