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); }
}
網上都是這種處理方式 寫死有越界的可能性
不知道有沒有其他的處理方式
問題解答
回答1:最好的方法是用Apache commons IO的IOUtils.toByteArray(inputStream),一行代碼解決。
回答2:int count = 0;while (count == 0) { count = inStream.available();}byte[] b = new byte[count];inStream.read(b);return b;
相關文章:
1. Span標簽2. docker-machine添加一個已有的docker主機問題3. redis啟動有問題?4. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””5. angular.js使用$resource服務把數據存入mongodb的問題。6. javascript - 計算面積函數代碼7. javascript - ng-options 設置默認選項,不是設置第一個哦,看清楚了!8. SessionNotFoundException:會話ID為null。調用quit()后使用WebDriver嗎?(硒)9. java - Spring MVC無法識別Controller導致返回的結果是404?10. java - Collections類里的swap函數,源碼為什么要新定義一個final的List型變量l指向傳入的list?
