首页 > 技术文章 > file 从InputStream读取byte[]示例

kelelipeng 2019-11-22 11:35 原文

file 从InputStream读取byte[]示例

  1. public static byte[] getStreamBytes(InputStream is) throws Exception {  
  2.     ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  3.     byte[] buffer = new byte[1024];  
  4.     int len = 0;  
  5.     while ((len = is.read(buffer)) != -1) {  
  6.         baos.write(buffer, 0, len);  
  7.     }  
  8.     byte[] b = baos.toByteArray();  
  9.     is.close();  
  10.     baos.close();  
  11.     return b;  
  12. }  
 
  1. default byte[] readFileBytes(InputStream is){  
  2.     byte[] data = null;  
  3.     try {  
  4.         if(is.available()==0){//严谨起见,一定要加上这个判断,不要返回data[]长度为0的数组指针  
  5.             return data;  
  6.         }  
  7.         data = new byte[is.available()];  
  8.         is.read(data);  
  9.         is.close();  
  10.         return data;  
  11.     } catch (IOException e) {  
  12.         LogCore.BASE.error("readFileBytes, err", e);  
  13.         return data;  
  14.     }  
  15. }
    1. 图片上传功能是我们web里面经常用到的,获得的方式也有很多种,这里我用的是request.getInputStream()获取文件流的方式。想要获取文件流有两种方式,附上代码

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      int length = request.getContentLength();//获取请求参数长度。
      byte[] bytes = new byte[length];//定义数组,长度为请求参数的长度
      DataInputStream dis = new DataInputStream(request.getInputStream);//获取请求内容,转成数据输入流
      int readcount = 0;//定义输入流读取数
      while(readcount < length){
       int aa= dis.read(bytes,readcount,length); //读取输入流,放入bytes数组,返回每次读取的数量
       readcount = aa + readcount; //下一次的读取开始从readcount开始
      }
      //读完之后bytes就是输入流的字节数组,将其转为字符串就能看到
      String bb = new String(bytes,"UTF-8");

      上面这种是利用读取输入流的方式,也可以用写入字节输入流的方式获取,就不需要获取请求长度了

      1
      2
      3
      4
      5
      6
      7
      8
      9
      DataInputStream dis = new DataInputStream(request.getInputStream());
      ByteArrayOutputStream baot = new ByteArrayOutputStream();
      byte[] bytes = new byte[1024]; //定义一个数组 用来读取
      int n = 0;//每次读取输入流的量
      while((n=dis.read(bytes))!=-1){
       baot.write(bytes); //将读取的字节流写入字节输出流
      }
      byte[] outbyte = boat.toByteArray();//将字节输出流转为自己数组。
      String bb = new String(outbyte,"UTF-8");

推荐阅读