/**
 * 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;
}

解决方案 »

  1.   

    方法不错,所耗空间大概是inStream读入空间的3倍
      

  2.   

    apache的IOUtil就有类似的函数
    http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.htmlstatic byte[] toByteArray(InputStream input) 
     
     
      

  3.   

    难道没人见过 ByteArrayOutputStream 么?
      

  4.   

    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();
    }