Convert InputStream to byte array in Java

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

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

30条回答
  •  逝去的感伤
    2020-11-21 12:41

    This is my copy-paste version:

    @SuppressWarnings("empty-statement")
    public static byte[] inputStreamToByte(InputStream is) throws IOException {
        if (is == null) {
            return null;
        }
        // Define a size if you have an idea of it.
        ByteArrayOutputStream r = new ByteArrayOutputStream(2048);
        byte[] read = new byte[512]; // Your buffer size.
        for (int i; -1 != (i = is.read(read)); r.write(read, 0, i));
        is.close();
        return r.toByteArray();
    }
    

提交回复
热议问题