Convert InputStream to byte array in Java

前端 未结 30 3499
無奈伤痛
無奈伤痛 2020-11-21 12:08

How do I read an entire InputStream into a byte array?

30条回答
  •  梦如初夏
    2020-11-21 12:33

    Here is an optimized version, that tries to avoid copying data bytes as much as possible:

    private static byte[] loadStream (InputStream stream) throws IOException {
       int available = stream.available();
       int expectedSize = available > 0 ? available : -1;
       return loadStream(stream, expectedSize);
    }
    
    private static byte[] loadStream (InputStream stream, int expectedSize) throws IOException {
       int basicBufferSize = 0x4000;
       int initialBufferSize = (expectedSize >= 0) ? expectedSize : basicBufferSize;
       byte[] buf = new byte[initialBufferSize];
       int pos = 0;
       while (true) {
          if (pos == buf.length) {
             int readAhead = -1;
             if (pos == expectedSize) {
                readAhead = stream.read();       // test whether EOF is at expectedSize
                if (readAhead == -1) {
                   return buf;
                }
             }
             int newBufferSize = Math.max(2 * buf.length, basicBufferSize);
             buf = Arrays.copyOf(buf, newBufferSize);
             if (readAhead != -1) {
                buf[pos++] = (byte)readAhead;
             }
          }
          int len = stream.read(buf, pos, buf.length - pos);
          if (len < 0) {
             return Arrays.copyOf(buf, pos);
          }
          pos += len;
       }
    }
    

提交回复
热议问题