|
55 | 55 | import org.apache.commons.io.output.ByteArrayOutputStream; |
56 | 56 | import org.apache.commons.io.output.NullOutputStream; |
57 | 57 | import org.apache.commons.io.output.StringBuilderWriter; |
| 58 | +import org.apache.commons.io.output.ThresholdingOutputStream; |
58 | 59 | import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; |
59 | 60 |
|
60 | 61 | /** |
@@ -2394,12 +2395,17 @@ public static BufferedReader toBufferedReader(final Reader reader, final int siz |
2394 | 2395 | * @param inputStream the {@code InputStream} to read. |
2395 | 2396 | * @return the requested byte array. |
2396 | 2397 | * @throws NullPointerException if the InputStream is {@code null}. |
2397 | | - * @throws IOException if an I/O error occurs. |
| 2398 | + * @throws IOException if an I/O error occurs or reading more than {@link Integer#MAX_VALUE} occurs. |
2398 | 2399 | */ |
2399 | 2400 | public static byte[] toByteArray(final InputStream inputStream) throws IOException { |
2400 | | - try (final UnsynchronizedByteArrayOutputStream output = new UnsynchronizedByteArrayOutputStream()) { |
2401 | | - copy(inputStream, output); |
2402 | | - return output.toByteArray(); |
| 2401 | + // We use a ThresholdingOutputStream to avoid reading AND writing more than Integer.MAX_VALUE. |
| 2402 | + try (final UnsynchronizedByteArrayOutputStream ubaOutput = new UnsynchronizedByteArrayOutputStream(); |
| 2403 | + final ThresholdingOutputStream thresholdOuput = new ThresholdingOutputStream(Integer.MAX_VALUE, os -> { |
| 2404 | + throw new IllegalArgumentException( |
| 2405 | + String.format("Cannot read more than %,d into a byte array", Integer.MAX_VALUE)); |
| 2406 | + }, os -> ubaOutput)) { |
| 2407 | + copy(inputStream, thresholdOuput); |
| 2408 | + return ubaOutput.toByteArray(); |
2403 | 2409 | } |
2404 | 2410 | } |
2405 | 2411 |
|
|
0 commit comments