java 从InputStream 获取字节数组
发布日期:2021-08-30 16:00:44 浏览次数:12 分类:技术文章

本文共 1370 字,大约阅读时间需要 4 分钟。

 中,如何从InputStream 读取字节数组呢?

方式一:

Java代码  
  1. /*** 
  2.      * Has been tested 
  3.      *  
  4.      * @param in 
  5.      * @return 
  6.      * @throws IOException 
  7.      */  
  8.     public static byte[] readBytes(InputStream in) throws IOException {  
  9.         byte[] temp = new byte[in.available()];  
  10.         byte[] result = new byte[0];  
  11.         int size = 0;  
  12.         while ((size = in.read(temp)) != -1) {  
  13.             byte[] readBytes = new byte[size];  
  14.             System.arraycopy(temp, 0, readBytes, 0, size);  
  15.             result = SystemUtil.mergeArray(result,readBytes);  
  16.         }  
  17.         return result;  
  18.     }  

 

 

方式二:

Java代码  
  1. public static byte[] readBytes3(InputStream in) throws IOException {  
  2.         BufferedInputStream bufin = new BufferedInputStream(in);  
  3.         int buffSize = BUFFSIZE_1024;  
  4.         ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);  
  5.   
  6.         // System.out.println("Available bytes:" + in.available());  
  7.   
  8.         byte[] temp = new byte[buffSize];  
  9.         int size = 0;  
  10.         while ((size = bufin.read(temp)) != -1) {  
  11.             out.write(temp, 0, size);  
  12.         }  
  13.         bufin.close();  
  14.   
  15.         byte[] content = out.toByteArray();  
  16.         return content;  
  17.     }  

 依赖的函数:

Java代码  
  1. /*** 
  2.      * 合并字节数组 
  3.      * @param a 
  4.      * @return 
  5.      */  
  6.     public static byte[] mergeArray(byte[]... a) {  
  7.         // 合并完之后数组的总长度  
  8.         int index = 0;  
  9.         int sum = 0;  
  10.         for (int i = 0; i < a.length; i++) {  
  11.             sum = sum + a[i].length;  
  12.         }  
  13.         byte[] result = new byte[sum];  
  14.         for (int i = 0; i < a.length; i++) {  
  15.             int lengthOne = a[i].length;  
  16.             if(lengthOne==0){  
  17.                 continue;  
  18.             }  
  19.             // 拷贝数组  
  20.             System.arraycopy(a[i], 0, result, index, lengthOne);  
  21.             index = index + lengthOne;  
  22.         }  
  23.         return result;  
  24.     }  

 

转载地址:https://blog.csdn.net/weixin_34038652/article/details/90621405 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java 删除空行
下一篇:mysql 类型

发表评论

最新留言

不错!
[***.144.177.141]2024年03月21日 16时43分30秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章