Home  >  Q&A  >  body text

java - inputstream is converted to byte array and the array is out of bounds

public static byte[] readInputStream(InputStream inStream) throws Exception {

    try {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }catch (Exception e){
        e.printStackTrace();
        throw new Exception(e);
    }

}

This is the way to deal with it all over the Internet. Writing to death may cross the line

I don’t know if there is any other way to deal with it

巴扎黑巴扎黑2735 days ago756

reply all(2)I'll reply

  • 阿神

    阿神2017-05-17 10:05:02

    The best way is to use Apache commons IO's IOUtils.toByteArray(inputStream), a one-line solution.

    reply
    0
  • 阿神

    阿神2017-05-17 10:05:02

            int count = 0;
            while (count == 0) {
                count = inStream.available();
            }
            byte[] b = new byte[count];
            inStream.read(b);
            return b;

    reply
    0
  • Cancelreply