ChunkedOutputStream.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.io.output;

  18. import java.io.FilterOutputStream;
  19. import java.io.IOException;
  20. import java.io.OutputStream;

  21. import org.apache.commons.io.IOUtils;
  22. import org.apache.commons.io.build.AbstractStreamBuilder;

  23. /**
  24.  * OutputStream which breaks larger output blocks into chunks. Native code may need to copy the input array; if the write buffer is very large this can cause
  25.  * OOME.
  26.  * <p>
  27.  * To build an instance, see {@link Builder}
  28.  * </p>
  29.  *
  30.  * @see Builder
  31.  * @since 2.5
  32.  */
  33. public class ChunkedOutputStream extends FilterOutputStream {

  34.     // @formatter:off
  35.     /**
  36.      * Builds a new {@link UnsynchronizedByteArrayOutputStream}.
  37.      *
  38.      * <p>
  39.      * Using File IO:
  40.      * </p>
  41.      * <pre>{@code
  42.      * ChunkedOutputStream s = ChunkedOutputStream.builder()
  43.      *   .setPath("over/there.out")
  44.      *   .setBufferSize(8192)
  45.      *   .get();
  46.      * }
  47.      * </pre>
  48.      * <p>
  49.      * Using NIO Path:
  50.      * </p>
  51.      * <pre>{@code
  52.      * ChunkedOutputStream s = ChunkedOutputStream.builder()
  53.      *   .setPath("over/there.out")
  54.      *   .setBufferSize(8192)
  55.      *   .get();
  56.      * }
  57.      * </pre>
  58.      *
  59.      * @see #get()
  60.      * @since 2.13.0
  61.      */
  62.     // @formatter:on
  63.     public static class Builder extends AbstractStreamBuilder<ChunkedOutputStream, Builder> {

  64.         /**
  65.          * Constructs a new builder of {@link ChunkedOutputStream}.
  66.          */
  67.         public Builder() {
  68.             // empty
  69.         }

  70.         /**
  71.          * Builds a new {@link ChunkedOutputStream}.
  72.          * <p>
  73.          * This builder uses the following aspects:
  74.          * </p>
  75.          * <ul>
  76.          * <li>{@link #getOutputStream()} is the target aspect.</li>
  77.          * <li>{@link #getBufferSize()} is used for the chunk size.</li>
  78.          * </ul>
  79.          *
  80.          * @return a new instance.
  81.          * @throws IllegalStateException         if the {@code origin} is {@code null}.
  82.          * @throws UnsupportedOperationException if the origin cannot be converted to an {@link OutputStream}.
  83.          * @throws IOException                   if an I/O error occurs converting to an {@link OutputStream} using {@link #getOutputStream()}.
  84.          * @see #getOutputStream()
  85.          * @see #getBufferSize()
  86.          * @see #getUnchecked()
  87.          */
  88.         @Override
  89.         public ChunkedOutputStream get() throws IOException {
  90.             return new ChunkedOutputStream(getOutputStream(), getBufferSize());
  91.         }

  92.     }

  93.     /**
  94.      * Constructs a new {@link Builder}.
  95.      *
  96.      * @return a new {@link Builder}.
  97.      * @since 2.13.0
  98.      */
  99.     public static Builder builder() {
  100.         return new Builder();
  101.     }

  102.     /**
  103.      * The maximum chunk size to us when writing data arrays
  104.      */
  105.     private final int chunkSize;

  106.     /**
  107.      * Constructs a new stream that uses a chunk size of {@link IOUtils#DEFAULT_BUFFER_SIZE}.
  108.      *
  109.      * @param stream the stream to wrap
  110.      * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
  111.      */
  112.     @Deprecated
  113.     public ChunkedOutputStream(final OutputStream stream) {
  114.         this(stream, IOUtils.DEFAULT_BUFFER_SIZE);
  115.     }

  116.     /**
  117.      * Constructs a new stream that uses the specified chunk size.
  118.      *
  119.      * @param stream    the stream to wrap
  120.      * @param chunkSize the chunk size to use; must be a positive number.
  121.      * @throws IllegalArgumentException if the chunk size is &lt;= 0
  122.      * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
  123.      */
  124.     @Deprecated
  125.     public ChunkedOutputStream(final OutputStream stream, final int chunkSize) {
  126.         super(stream);
  127.         if (chunkSize <= 0) {
  128.             throw new IllegalArgumentException("chunkSize <= 0");
  129.         }
  130.         this.chunkSize = chunkSize;
  131.     }

  132.     int getChunkSize() {
  133.         return chunkSize;
  134.     }

  135.     /**
  136.      * Writes the data buffer in chunks to the underlying stream
  137.      *
  138.      * @param data      the data to write
  139.      * @param srcOffset the offset
  140.      * @param length    the length of data to write
  141.      * @throws IOException if an I/O error occurs.
  142.      */
  143.     @Override
  144.     public void write(final byte[] data, final int srcOffset, final int length) throws IOException {
  145.         int bytes = length;
  146.         int dstOffset = srcOffset;
  147.         while (bytes > 0) {
  148.             final int chunk = Math.min(bytes, chunkSize);
  149.             out.write(data, dstOffset, chunk);
  150.             bytes -= chunk;
  151.             dstOffset += chunk;
  152.         }
  153.     }

  154. }