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. python - beautifulsoup獲取網頁內容的問題2. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題3. docker鏡像push報錯4. docker - 如何修改運行中容器的配置5. docker-machine添加一個已有的docker主機問題6. fragment - android webView 返回后怎么禁止重新渲染?7. docker不顯示端口映射呢?8. android studio總是在processes running好久9. dockerfile - [docker build image失敗- npm install]10. angular.js - Angular 2 + Django構建的Web應用, 如何合理搭配 ?
