file 從InputStream讀取byte[]示例


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");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM