]> source.dussan.org Git - poi.git/commitdiff
fix issue in IOUtils.toByteArrayWithMaxLength
authorPJ Fanning <fanningpj@apache.org>
Fri, 11 Mar 2022 22:37:29 +0000 (22:37 +0000)
committerPJ Fanning <fanningpj@apache.org>
Fri, 11 Mar 2022 22:37:29 +0000 (22:37 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1898863 13f79535-47bb-0310-9956-ffa450edef68

poi/src/main/java/org/apache/poi/util/IOUtils.java

index e9c83a8f631ae372466b5b2620b17999623da341..f5940d95554d1cd15b2170e205f70f1fbc83060f 100644 (file)
@@ -54,10 +54,32 @@ public final class IOUtils {
      */
     private static int BYTE_ARRAY_MAX_OVERRIDE = -1;
 
+    /**
+     * The max init size of ByteArrayOutputStream.
+     * -1 means init size of ByteArrayOutputStream could be up to Integer.MAX_VALUE
+     */
+    private static int MAX_BYTE_ARRAY_INIT_SIZE = -1;
+
     private IOUtils() {
         // no instances of this class
     }
 
+    /**
+     * @param maxOverride the max init size of ByteArrayOutputStream.
+     * -1 (the default) means init size of ByteArrayOutputStream could be up to Integer.MAX_VALUE
+     */
+    public static void setMaxByteArrayInitSize(final int maxOverride) {
+        MAX_BYTE_ARRAY_INIT_SIZE = maxOverride;
+    }
+
+    /**
+     * @return the max init size of ByteArrayOutputStream.
+     * -1 (the default) means init size of ByteArrayOutputStream could be up to Integer.MAX_VALUE
+     */
+    public static int getMaxByteArrayInitSize() {
+        return MAX_BYTE_ARRAY_INIT_SIZE;
+    }
+
     /**
      * If this value is set to &gt; 0, {@link #safelyAllocate(long, int)} will ignore the
      * maximum record length parameter.
@@ -202,7 +224,10 @@ public final class IOUtils {
         }
 
         final int derivedLen = Math.min(length, derivedMaxLength);
-        final int bufferLen = isLengthKnown ? derivedLen : Math.min(4096, derivedLen);
+        int bufferLen = isLengthKnown ? derivedLen : Math.min(4096, derivedLen);
+        if (bufferLen > MAX_BYTE_ARRAY_INIT_SIZE && MAX_BYTE_ARRAY_INIT_SIZE > 0) {
+            bufferLen = Math.min(bufferLen, MAX_BYTE_ARRAY_INIT_SIZE);
+        }
         try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(bufferLen)) {
             byte[] buffer = new byte[4096];
             int totalBytes = 0, readBytes;