java - inputstream轉為byte數(shù)組 數(shù)組越界
問題描述
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); }
}
網(wǎng)上都是這種處理方式 寫死有越界的可能性
不知道有沒有其他的處理方式
問題解答
回答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. javascript - immutable配合react提升性能?2. javascript - sublime快鍵鍵問題3. css - 寫頁面遇到個布局問題,求大佬們幫解答,在線等,急!~4. 配置Apache時,添加對PHP的支持時語法錯誤5. phpstudy8.1支持win11系統(tǒng)嗎?6. javascript - nodejs關于進程間發(fā)送句柄的一點疑問7. javascript - 移動端上不能實現(xiàn)拖拽布局嗎?8. 實現(xiàn)bing搜索工具urlAPI提交9. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務器還是不能訪問?10. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化

網(wǎng)公網(wǎng)安備