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 - 在 model里定義的 引用表模型時(shí),model為undefined。2. css3 - 這個右下角折角用css怎么畫出來?3. javascript - canvas 裁剪空白區(qū)域4. atom開始輸入!然后按tab只有空格出現(xiàn)沒有html格式出現(xiàn)5. css3 - 沒明白盒子的height隨width的變化這段css是怎樣實(shí)現(xiàn)的?6. java - 根據(jù)月份查詢多個表里的內(nèi)容怎么實(shí)現(xiàn)好?7. apache - 想把之前寫的單機(jī)版 windows 軟件改成網(wǎng)絡(luò)版,讓每個用戶可以注冊并登錄。類似 qq 的登陸,怎么架設(shè)服務(wù)器呢?8. dockerfile - [docker build image失敗- npm install]9. python3.x - c++調(diào)用python310. android - 課程表點(diǎn)擊后浮動后邊透明可以左右滑動的界面是什么?
