inputstream转为byte数组 数组越界

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);
    }

}

网上都是这种处理方式 写死有越界的可能性

不知道有没有其他的处理方式

阅读 5.2k
2 个回答

最好的方法是用Apache commons IO的IOUtils.toByteArray(inputStream),一行代码解决。

        int count = 0;
        while (count == 0) {
            count = inStream.available();
        }
        byte[] b = new byte[count];
        inStream.read(b);
        return b;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题