首頁  >  問答  >  主體

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

}

網路上都是這種處理方式 寫死有越界的可能性

不知道有沒有其他的處理方式

巴扎黑巴扎黑2712 天前724

全部回覆(2)我來回復

  • 阿神

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

    最好的方法是用Apache commons IO的IOUtils.toByteArray(inputStream),一行程式碼解決。

    回覆
    0
  • 阿神

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

    雷雷

    回覆
    0
  • 取消回覆