Convert InputStream to byte array in Java

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

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

30条回答
  •  感动是毒
    2020-11-21 12:46

    I use this.

    public static byte[] toByteArray(InputStream is) throws IOException {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                byte[] b = new byte[4096];
                int n = 0;
                while ((n = is.read(b)) != -1) {
                    output.write(b, 0, n);
                }
                return output.toByteArray();
            } finally {
                output.close();
            }
        }
    

提交回复
热议问题