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. html5 - datatables 加載不出來數據。2. node.js - mongodb查找子對象的名稱為某個值的對象的方法3. 測試自動化html元素選擇器元素ID或DataAttribute [關閉]4. html5和Flash對抗是什么情況?5. 利用IPMI遠程安裝centos報錯!6. javascript - QQ第三方登錄的問題7. 在mac下出現了兩個docker環境8. 運行python程序時出現“應用程序發生異常”的內存錯誤?9. spring-mvc - spring-session-redis HttpSessionListener失效10. 正在使用electron和node.js做桌面應用,需要實時監聽是否有網絡連接,node或者electron是否可以做到

網公網安備