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. html - 用ajax提交表單后,返回驗證數據在頁面location.href跳轉到主頁,怎么傳遞session給主頁2. docker-machine添加一個已有的docker主機問題3. java - mybatis會自己緩存自己生成過的prestatement嗎4. java-ee - JAVA的注解@Api和@ApiOperation的作用是什么,怎么跳轉頁面的5. apache - nginx 日志刪除后 重新建一個文件 就打不了日志了6. node.js - node express 中ajax post請求參數接收不到?7. java - tomcat服務經常晚上會掛,求解?8. java - 原生CGLib內部方法互相調用時可以代理,但基于CGLib的Spring AOP卻代理失效,為什么?9. 怎么能做出標簽切換頁的效果,(文字內容隨動)10. mysql - mongo如何對一個collection進行順序上的調整呢?
