一切皆可抽象

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

          InputStream to Byte[]

          Posted on 2007-03-13 17:35 鋒出磨礪 閱讀(6468) 評論(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,這樣大的流就會內存溢出。直接到文件硬盤輸出最好??淳唧w的應用場景了。

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

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

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

          2009-12-22 12:04 by eagle-daiq
          不錯。
          主站蜘蛛池模板: 喀喇沁旗| 蛟河市| 东至县| 高雄市| 武山县| 塔河县| 历史| 涿鹿县| 汨罗市| 积石山| 夏邑县| 合山市| 丹棱县| 合阳县| 桐乡市| 江陵县| 濮阳市| 麻江县| 西畴县| 东丽区| 台安县| 杭锦后旗| 德安县| 祁阳县| 东阳市| 准格尔旗| 合水县| 礼泉县| 仙桃市| 河西区| 通城县| 乌海市| 锡林浩特市| 乐山市| 保亭| 蓬安县| 绥德县| 陈巴尔虎旗| 顺平县| 龙井市| 南部县|