一切皆可抽象

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

          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,這樣大的流就會內存溢出。直接到文件硬盤輸出最好。看具體的應用場景了。

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

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

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

          2009-12-22 12:04 by eagle-daiq
          不錯。
          主站蜘蛛池模板: 美姑县| 柘荣县| 缙云县| 朝阳区| 淮南市| 九台市| 余姚市| 湘潭县| 建始县| 通江县| 聂拉木县| 大余县| 旬阳县| 大荔县| 台南市| 大石桥市| 南江县| 西平县| 镇江市| 乐至县| 中牟县| 云浮市| 大冶市| 砀山县| 随州市| 北辰区| 霍州市| 仁寿县| 射阳县| 南溪县| 石城县| 丘北县| 苍梧县| 城市| 宕昌县| 上饶县| 定日县| 公主岭市| 丹棱县| 建水县| 眉山市|