diff --git a/src/main/java/org/apache/commons/compress/utils/IOUtils.java b/src/main/java/org/apache/commons/compress/utils/IOUtils.java index 04e9eb9facf..81f8f915062 100644 --- a/src/main/java/org/apache/commons/compress/utils/IOUtils.java +++ b/src/main/java/org/apache/commons/compress/utils/IOUtils.java @@ -31,6 +31,7 @@ import java.nio.file.LinkOption; import org.apache.commons.io.FileUtils; +import org.apache.commons.io.output.NullOutputStream; /** * Utility functions. @@ -138,15 +139,7 @@ public static long copyRange(final InputStream input, final long length, final O throw new IllegalArgumentException("bufferSize must be bigger than 0"); } final byte[] buffer = new byte[(int) Math.min(bufferSize, Math.max(0, length))]; - int n = 0; - long count = 0; - while (count < length && -1 != (n = input.read(buffer, 0, (int) Math.min(length - count, buffer.length)))) { - if (output != null) { - output.write(buffer, 0, n); - } - count += n; - } - return count; + return org.apache.commons.io.IOUtils.copyLarge(input, output != null ? output : NullOutputStream.INSTANCE, 0, length, buffer); } /** diff --git a/src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java b/src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java index 94a29bd50b2..d5ddf22c493 100644 --- a/src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java +++ b/src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java @@ -108,9 +108,12 @@ public void testCopyRangeStopsIfThereIsNothingToCopyAnymore() throws IOException } @Test - public void testCopyRangeThrowsOnZeroBufferSize() { + public void testCopyRangeThrowsOnZeroBufferSize() throws IOException { assertThrows(IllegalArgumentException.class, () -> IOUtils.copyRange(new ByteArrayInputStream(ByteUtils.EMPTY_BYTE_ARRAY), 5, new ByteArrayOutputStream(), 0)); + assertEquals(0, IOUtils.copyRange(new ByteArrayInputStream(ByteUtils.EMPTY_BYTE_ARRAY), 5, new ByteArrayOutputStream(), 1)); + assertEquals(0, IOUtils.copyRange(new ByteArrayInputStream(ByteUtils.EMPTY_BYTE_ARRAY), 5, null, 1)); + assertEquals(1, IOUtils.copyRange(new ByteArrayInputStream(new byte[1]), 5, null, 1)); } @Test