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. nignx - docker内nginx 80端口被占用2. docker安装后出现Cannot connect to the Docker daemon.3. golang - 用IDE看docker源码时的小问题4. javascript - 修改表单多选项时和后台同事配合的问题。5. redis - 究竟是选择微信小程序自带的统计工具还是自己开发一个数据统计的代码?6. javascript - 怎么实现点击表格中的某一行然后就在表单处出现表格中的对应的属性值啊7. docker绑定了nginx端口 外部访问不到8. css - 使用blur()滤镜为什么有透明的效果9. dockerfile - [docker build image失败- npm install]10. 如何解决docker宿主机无法访问容器中的服务?

网公网安备