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)

          隨筆分類

          隨筆檔案

          收藏夾

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 呼伦贝尔市| 梓潼县| 新巴尔虎右旗| 航空| 元江| 日照市| 温泉县| 双鸭山市| 顺义区| 通化县| 黑河市| 砚山县| 娱乐| 柞水县| 噶尔县| 沙雅县| 石景山区| 贺兰县| 民丰县| 元谋县| 永川市| 大新县| 济阳县| 临城县| 达尔| 寿光市| 定兴县| 开封县| 恭城| 正阳县| 奎屯市| 平潭县| 尖扎县| 陵川县| 沂南县| 东莞市| 桃园市| 涿州市| 奉化市| 安吉县| 长沙县|