Java的InputStream操做的坑

一、in.available()该方法不能保证全部的流已到达java

//这种写法在网络请求数据时会致使接收数据不完整 
byte[] input = new byte[in.available()];
 in.read(input);

二、二进制流读取错误方式数组

byte[] buffer = new byte[1024];
  BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while(bis.read(buffer) != -1){ //这个写法会致使buffer数组没有清空,数据会比原数据流多
         bos.write(buffer);
    }
 byte[] input = bos.toByteArray();

三、正确的读取方式网络

int n;
            byte[] buffer = new byte[1024];
            BufferedInputStream bis = new BufferedInputStream(in);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while((n=bis.read(buffer)) != -1){
                bos.write(buffer,0,n);//每次保证只写入读到的流位置
            }
            byte[] input = bos.toByteArray();

四、快速读取网络流工具

//使用现成工具读取 
URL imgUrl = new URL(path);          
 byte[] input = IOUtils.toByteArray(imgUrl);
相关文章
相关标签/搜索