Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/main/java/org/apache/commons/io/IOUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -2957,6 +2957,7 @@ public static byte[] toByteArray(final InputStream input, final long size) throw
* @param input the input to read, not null.
* @param size the size of the input to read, where 0 < {@code size} <= length of input.
* @return byte [] of length {@code size}.
* @throws EOFException if the end of the input is reached before reading {@code size} bytes.
* @throws IOException if an I/O error occurs or input length is smaller than parameter {@code size}.
* @throws IllegalArgumentException if {@code size} is less than zero.
*/
Expand All @@ -2974,7 +2975,7 @@ static byte[] toByteArray(final IOTriFunction<byte[], Integer, Integer, Integer>
offset += read;
}
if (offset != size) {
throw new IOException("Unexpected read size, current: " + offset + ", expected: " + size);
throw new EOFException("Unexpected read size, current: " + offset + ", expected: " + size);
}
return data;
}
Expand Down
11 changes: 10 additions & 1 deletion src/test/java/org/apache/commons/io/IOUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ static Stream<Arguments> testToByteArray_InputStream_Size_BufferSize_Throws() {
Arguments.of(-1, 128, IllegalArgumentException.class),
// Invalid buffer size
Arguments.of(0, 0, IllegalArgumentException.class),
// Huge size: should not cause OutOfMemoryError
// Truncation with requested size < chunk size
Arguments.of(64, 128, EOFException.class),
// Truncation with requested size > chunk size
Arguments.of(Integer.MAX_VALUE, 128, EOFException.class));
}

Expand Down Expand Up @@ -1757,6 +1759,13 @@ void testToByteArray_InputStream_Size() throws Exception {
}
}

@Test
void testToByteArray_InputStream_Size_Truncated() throws Exception {
try (InputStream in = new NullInputStream(0)) {
assertThrows(EOFException.class, () -> IOUtils.toByteArray(in, 1), "Should have failed with EOFException");
}
}

@ParameterizedTest
@MethodSource
void testToByteArray_InputStream_Size_BufferSize_Succeeds(final byte[] data, final int size, final int bufferSize) throws IOException {
Expand Down
Loading