一切皆可抽象

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

          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 九層樓
          謝謝?。?!很好!?。?/div>

          # 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
          不錯。
          主站蜘蛛池模板: 天峻县| 连州市| 沙河市| 会同县| 沈丘县| 峨山| 长宁县| 枞阳县| 盐亭县| 郸城县| 镇安县| 桃园市| 民丰县| 平泉县| 洮南市| 二手房| 旬邑县| 正安县| 盐源县| 安远县| 宁蒗| 九龙县| 兰溪市| 斗六市| 什邡市| 会昌县| 措勤县| 舒城县| 游戏| 金华市| 西林县| 临猗县| 砀山县| 攀枝花市| 鄂托克旗| 岑溪市| 彩票| 琼中| 西宁市| 敦煌市| 遵化市|