java - inputstream流讀到最后為什么沒有返回 -1 ?
問題描述
InputStream fileSource = req.getInputStream();String tempFile = '/home/joy/桌面/tempFile';FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);byte[] bytes = new byte[10 * 1024];int i = 0;while ((i = fileSource.read(bytes, 0, bytes.length)) != -1) { System.out.println('已讀字節:' + i + ', 剩余字節: ' + fileSource.available()); System.out.println(new String(bytes)); tempFileOutputStream.write(bytes); tempFileOutputStream.flush(); if (fileSource.available() < bytes.length) {bytes = new byte[fileSource.available()]; }}tempFileOutputStream.close();fileSource.close();
為什么該流讀完的時候并沒有返回-1,而是返回0,導致無限循環.(上傳文檔類型文件不會,字節文件就會發生這種情況)
問題解答
回答1:應該是你最后對buffer的處理導致剛剛好讀取完文件吧
if (fileSource.available() < bytes.length) { bytes = new byte[fileSource.available()];}
一般情況下不需要重設buffer的大小
相關文章:
1. javascript - node.js promise沒用2. golang - 用IDE看docker源碼時的小問題3. yii2中restful配置好后在nginx下報404錯誤4. 算法 - python 給定一個正整數a和一個包含任意個正整數的 列表 b,求所有<=a 的加法組合5. android 如何實現如圖中的鍵盤上的公式及edittext的內容展示呢6. java - 我在用Struts2上傳文件時,報以下錯誤怎么回事?7. c++ - 如何正確的使用QWebEngineView?8. PHP注冊功能9. mysql - 求SQL語句10. MySQL如何實現表中再嵌套一個表?
