< prev index next >
src/java.base/share/classes/java/io/InputStream.java
Print this page
@@ -23,10 +23,11 @@
* questions.
*/
package java.io;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
/**
* This abstract class is the superclass of all classes representing
@@ -227,34 +228,49 @@
* be required to store the bytes.
*
* @since 9
*/
public byte[] readAllBytes() throws IOException {
+ ArrayList<byte[]> list = new ArrayList<byte[]>(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;
+ nread = 0;
}
- buf = Arrays.copyOf(buf, capacity);
+
+ 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 (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
+
+ return output;
}
/**
* Reads the requested number of bytes from the input stream into the given
* byte array. This method blocks until {@code len} bytes of input data have
< prev index next >