首页  >  问答  >  正文

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

}

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

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

巴扎黑巴扎黑2713 天前731

全部回复(2)我来回复

  • 阿神

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

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

    回复
    0
  • 阿神

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

    雷雷

    回复
    0
  • 取消回复