java - inputstream轉(zhuǎn)為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;
相關(guān)文章:
1. javascript - 如圖,百度首頁,查看源代碼為什么什么都沒有?2. android - weex 項目createInstanceReferenceError: Vue is not defined3. html - 關(guān)于CSS實現(xiàn)border的0.5px設(shè)置?4. javascript - 原生APP內(nèi)嵌H5頁面分享到微信朋友圈,二次分享問題。5. javascript - 為什么clearInterVal不起作用呢?6. PHPExcel表格導入數(shù)據(jù)庫怎么導入7. android - 哪位大神知道java后臺的api接口的對象傳到前端后輸入日期報錯,是什么情況?求大神指點8. pdo 寫入到數(shù)據(jù)庫的內(nèi)容為中文的時候?qū)懭雭y碼9. PHP類封裝的插入數(shù)據(jù),總是插入不成功,返回false;10. vue2.0+webpack 如何使用bootstrap?
