< prev index next >
src/java.base/share/classes/java/io/InputStream.java
Print this page
*** 23,32 ****
--- 23,33 ----
* 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,260 ****
* be required to store the bytes.
*
* @since 9
*/
public byte[] readAllBytes() throws IOException {
! byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
! int capacity = buf.length;
! int nread = 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)
! nread += n;
! // 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);
}
! return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
}
/**
* 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
--- 228,272 ----
* be required to store the bytes.
*
* @since 9
*/
public byte[] readAllBytes() throws IOException {
! var bufs = new ArrayList<byte[]>(8);
! var buf = new byte[DEFAULT_BUFFER_SIZE];
! int total = 0;
int n;
! do {
! int 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;
! var copy = (n < 0 && nread == DEFAULT_BUFFER_SIZE) ?
! buf : Arrays.copyOf(buf, nread);
! bufs.add(copy);
}
! } while (n >= 0); // if the last call to read returned -1, then break
!
! if (bufs.size() == 1) {
! return bufs.get(0);
! }
!
! var result = new byte[total];
! int offset = 0;
! for (var b : bufs) {
! System.arraycopy(b, 0, result, offset, b.length);
! offset += b.length;
! }
!
! return result;
}
/**
* 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 >