--- old/src/java.base/share/classes/java/io/InputStream.java 2017-12-19 11:54:58.000000000 -0800 +++ new/src/java.base/share/classes/java/io/InputStream.java 2017-12-19 11:54:57.000000000 -0800 @@ -25,6 +25,7 @@ package java.io; +import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; @@ -229,30 +230,45 @@ * @since 9 */ public byte[] readAllBytes() throws IOException { + ArrayList list = new ArrayList(128); byte[] buf = new byte[DEFAULT_BUFFER_SIZE]; - int capacity = buf.length; int nread = 0; + int total = 0; int n; for (;;) { - // read to EOF which may read more or less than initial buffer size - while ((n = read(buf, nread, capacity - nread)) > 0) + // read to EOF which may read more or less than buffer size + while ((n = read(buf, nread, buf.length - nread)) > 0) nread += n; + if (nread > 0) { + if (MAX_BUFFER_SIZE - total < nread) { + throw new OutOfMemoryError("Required array size too large"); + } + total += nread; + list.add(Arrays.copyOf(buf, nread)); + } + // if the last call to read returned -1, then we're done if (n < 0) break; - // need to allocate a larger buffer - if (capacity <= MAX_BUFFER_SIZE - capacity) { - capacity = capacity << 1; - } else { - if (capacity == MAX_BUFFER_SIZE) - throw new OutOfMemoryError("Required array size too large"); - capacity = MAX_BUFFER_SIZE; - } - buf = Arrays.copyOf(buf, capacity); + nread = 0; } - return (capacity == nread) ? buf : Arrays.copyOf(buf, nread); + + if (list.size() == 1) { + return list.get(0); + } + + byte[] output = new byte[total]; + int offset = 0; + int numCached = list.size(); + for (int i = 0; i < numCached; i++) { + byte[] b = list.get(i); + System.arraycopy(b, 0, output, offset, b.length); + offset += b.length; + } + + return output; } /**