一切皆可抽象

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

          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[]  回復(fù)  更多評論   

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

          # re: InputStream to Byte[]  回復(fù)  更多評論   

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

          # re: InputStream to Byte[]  回復(fù)  更多評論   

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

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

          # re: InputStream to Byte[]  回復(fù)  更多評論   

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

          # re: InputStream to Byte[]  回復(fù)  更多評論   

          2009-12-22 12:04 by eagle-daiq
          不錯。
          主站蜘蛛池模板: 无极县| 山东省| 垫江县| 宁南县| 浏阳市| 新宾| 东安县| 台湾省| 蚌埠市| 桃江县| 安岳县| 曲阳县| 敦化市| 肇东市| 宿州市| 阜南县| 龙南县| 三明市| 原平市| 景宁| 三亚市| 广德县| 邯郸市| 东莞市| 开原市| 曲松县| 广水市| 白山市| 丹棱县| 开化县| 汉阴县| 莆田市| 陆良县| 东乌| 鹤岗市| 通山县| 桂平市| 谢通门县| 长宁区| 大余县| 浮梁县|