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 一堣而安 閱讀(1016) 評論(0)  編輯  收藏 所屬分類: java

          導航

          統計

          常用鏈接

          留言簿(1)

          隨筆分類

          隨筆檔案

          收藏夾

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 新巴尔虎左旗| 杭锦后旗| 前郭尔| 萝北县| 封开县| 沛县| 密云县| 海宁市| 额敏县| 木兰县| 新兴县| 芦山县| 安仁县| 聂拉木县| 蕲春县| 曲靖市| 徐闻县| 马关县| 延长县| 盐源县| 金堂县| 陆丰市| 会同县| 贵溪市| 农安县| 横山县| 响水县| 沙河市| 永顺县| 临西县| 上犹县| 周至县| 玉环县| 虞城县| 观塘区| 水城县| 凯里市| 铜川市| 抚松县| 砀山县| 尉氏县|