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. python - pig latin问题 总是出现list/string index out of range2. 安装mysql,完成时提示的是用户名root,在终端查看版本时显示的不是root,请问这怎么解决3. javascript - sublime已经安装了babel插件和sublimelinter-jshint为什么还是显示es6语法错误?4. css3 - canvas在IOS8中不兼容。画不出来。5. 为什么HTML5规范中会包含一些和html无关的东西?如本地存储等。6. 闯关的第二个问题的答案是错的吧?7. css3 - img垂直水平居中问题8. javascript - angularJS select标签问题9. javascript - nginx 反向代理 js跨域问题?10. python - Pycharm调试代码进行列表遍历时,如何直接赋值指定元素

网公网安备