当前位置: 代码迷 >> J2SE >> 今天看到一个方法,觉得写得不错,共享一上
  详细解决方案

今天看到一个方法,觉得写得不错,共享一上

热度:4734   发布时间:2013-02-25 00:00:00.0
今天看到一个方法,觉得写得不错,共享一下
Java code
/**     * Reads this input stream and returns contents as a byte[]     * from:aspectjweaver.jar     */    public static byte[] readAsByteArray(InputStream inStream) throws IOException {        int size = 1024;        byte[] buff = new byte[size];        int readSoFar = 0;        while (true) {            int nRead = inStream.read(buff, readSoFar, size - readSoFar);            if (nRead == -1) {                break;            }            readSoFar += nRead;            if (readSoFar == size) {                int newSize = size * 2;                byte[] newBuff = new byte[newSize];                System.arraycopy(buff, 0, newBuff, 0, size);                buff = newBuff;                size = newSize;            }        }        byte[] newBuff = new byte[readSoFar];        System.arraycopy(buff, 0, newBuff, 0, readSoFar);        return newBuff;    }


------解决方案--------------------------------------------------------
谢谢楼主,学习!
------解决方案--------------------------------------------------------
Get it....
------解决方案--------------------------------------------------------
探讨
Java code

/**
* Reads this input stream and returns contents as a byte[]
* from:aspectjweaver.jar
*/
public static byte[] readAsByteArray(InputStream inStream) throws IOException ……

------解决方案--------------------------------------------------------
apache的IOUtil就有类似的函数。。。
http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils

static byte[] toByteArray(InputStream input) 
 
 


------解决方案--------------------------------------------------------
谢谢楼主!
------解决方案--------------------------------------------------------
good
------解决方案--------------------------------------------------------
解释一下,没看懂
------解决方案--------------------------------------------------------
难道没人见过 ByteArrayOutputStream 么?
------解决方案--------------------------------------------------------
Java code
public static byte[] readStreamAsBytes(InputStream in) throws IOException {    if (in == null) {        return null;    }    ByteArrayOutputStream out = new ByteArrayOutputStream();    byte[] bys = new byte[4096];    for (int p = -1; (p = in.read(bys)) != -1; ) {        out.write(bys, 0, p);    }    return out.toByteArray();}
------解决方案--------------------------------------------------------
good good .......
------解决方案--------------------------------------------------------
感谢分享哈
------解决方案--------------------------------------------------------
看看,学习
------解决方案--------------------------------------------------------
谢谢,虽然没看懂
------解决方案--------------------------------------------------------
好方法
  相关解决方案