一切皆可抽象

大而无形 庖丁解牛 厚积薄发 涤虑玄览
   ::  ::  ::  ::  :: 管理

InputStream to Byte[]

Posted on 2007-03-13 17:35 锋出磨砺 阅读(6441) 评论(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.blogjava.net/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
不错。

只有注册用户登录后才能发表评论。


网站导航: