tinguo002

           

          java中InputStream轉化為byte[]數組

          在commons-io包中org.apache.commons.io.IOUtils類的toByteArray(InputStream input)已經有實現了,我們可以參考下思路,完成我們的方法,我們可以用類似下面的代碼實現inputStream轉化為byte[]數組
          public static byte[] toByteArray(InputStream input) throws IOException {
              ByteArrayOutputStream output = new ByteArrayOutputStream();
              byte[] buffer = new byte[4096];
              int n = 0;
              while (-1 != (n = input.read(buffer))) {
                  output.write(buffer, 0, n);
              }
              return output.toByteArray();
          }
          

          下面是IOUtils中摘錄出與toByteArray相關的方法

          org.apache.commons.io.IOUtils.toByteArray
          
          方法如下:
          public static byte[] toByteArray(InputStream input)
            throws IOException
          {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            copy(input, output);
            return output.toByteArray();
          }
          
          public static int copy(InputStream input, OutputStream output)
            throws IOException
          {
            long count = copyLarge(input, output);
            if (count > 2147483647L) {
              return -1;
            }
            return (int)count;
          }
          
          public static long copyLarge(InputStream input, OutputStream output)
            throws IOException
          {
            byte[] buffer = new byte[4096];
            long count = 0L;
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
              output.write(buffer, 0, n);
              count += n;
            }
            return count;
          }

          文章詳細出處:http://blog.csdn.net/zdwzzu2006/article/details/7745827


          歡迎大家訪問我的個人網站 萌萌的IT人

          posted on 2014-08-04 21:12 一堣而安 閱讀(1024) 評論(0)  編輯  收藏 所屬分類: java

          導航

          統計

          常用鏈接

          留言簿(1)

          隨筆分類

          隨筆檔案

          收藏夾

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 思南县| 田林县| 昌黎县| 长宁县| 万安县| 沂水县| 林口县| 潞西市| 外汇| 平谷区| 上思县| 噶尔县| 岑巩县| 肥乡县| 房产| 体育| 新和县| 浮山县| 苏尼特左旗| 从化市| 渑池县| 岳西县| 新闻| 曲水县| 瑞金市| 涞水县| 桂平市| 樟树市| 称多县| 井冈山市| 徐水县| 鹤壁市| 阜新| 桐乡市| 梅州市| 赤城县| 林西县| 遂川县| 禹州市| 宜都市| 济南市|