一切皆可抽象

          大而無形 庖丁解牛 厚積薄發 滌慮玄覽
             ::  ::  ::  ::  :: 管理

          InputStream to Byte[]

          Posted on 2007-03-13 17:35 鋒出磨礪 閱讀(6464) 評論(5)  編輯  收藏 所屬分類: java算法
          public static byte[] getBytes(InputStream is)
          ??? throws Exception
          ??? {
          ??????? byte[] data = null;
          ???????
          ??????? Collection chunks = new ArrayList();
          ??????? byte[] buffer = new byte[1024*1000];
          ??????? int read = -1;
          ??????? int size = 0;
          ???????
          ??????? while((read=is.read(buffer))!=-1)
          ??????? {
          ??????????? if(read>0)
          ??????????? {
          ??????????????? byte[] chunk = new byte[read];
          ??????????????? System.arraycopy(buffer,0,chunk,0,read);
          ??????????????? chunks.add(chunk);
          ??????????????? size += chunk.length;
          ??????????? }
          ??????? }??????
          ???????
          ??????? if(size>0)
          ??????? {
          ??????????? ByteArrayOutputStream bos = null;
          ??????????? try
          ??????????? {
          ??????????????? bos = new ByteArrayOutputStream(size);
          ??????????????? for(Iterator itr=chunks.iterator();itr.hasNext();)
          ??????????????? {
          ??????????????????? byte[] chunk = (byte[])itr.next();
          ??????????????????? bos.write(chunk);
          ??????????????? }
          ??????????????? data = bos.toByteArray();
          ??????????? }
          ??????????? finally
          ??????????? {
          ??????????????? if(bos!=null)
          ??????????????? {
          ??????????????????? bos.close();
          ??????????????? }
          ??????????? }
          ??????? }
          ??????? return data;
          ??? }

          評論

          # re: InputStream to Byte[]  回復  更多評論   

          2007-06-18 13:48 by 九層樓
          謝謝!!!很好!!!

          # re: InputStream to Byte[]  回復  更多評論   

          2008-02-28 14:07 by luffy
          很好~ 很強大~ 如果不知道流的大小呢~

          # re: InputStream to Byte[]  回復  更多評論   

          2008-02-28 20:45 by itaogo
          如果想計算流的大小,可以參考
          http://www.aygfsteel.com/itaogo/archive/2007/03/13/103594.html

          一般不建議使用InputStream to byte,這樣大的流就會內存溢出。直接到文件硬盤輸出最好。看具體的應用場景了。

          # re: InputStream to Byte[]  回復  更多評論   

          2009-02-16 10:49 by dongzgguang
          太棒了,謝謝

          # re: InputStream to Byte[]  回復  更多評論   

          2009-12-22 12:04 by eagle-daiq
          不錯。
          主站蜘蛛池模板: 荆州市| 阿拉善右旗| 天台县| 梅河口市| 新邵县| 枣庄市| 台安县| 万州区| 青浦区| 台山市| 维西| 香河县| 清新县| 高雄市| 龙口市| 津市市| 永胜县| 新兴县| 内黄县| 崇左市| 恩平市| 上蔡县| 呼玛县| 济宁市| 阿巴嘎旗| 股票| 华阴市| 建宁县| 读书| 龙南县| 无极县| 夹江县| 巢湖市| 平利县| 巨鹿县| 克什克腾旗| 工布江达县| 招远市| 舟曲县| 长海县| 盘锦市|