1 /*
   2  * Copyright (c) 1994, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.io;
  27 
  28 import java.nio.charset.Charset;
  29 import java.util.Arrays;
  30 import java.util.Objects;
  31 
  32 /**
  33  * This class implements an output stream in which the data is
  34  * written into a byte array. The buffer automatically grows as data
  35  * is written to it.
  36  * The data can be retrieved using {@code toByteArray()} and
  37  * {@code toString()}.
  38  * <p>
  39  * Closing a {@code ByteArrayOutputStream} has no effect. The methods in
  40  * this class can be called after the stream has been closed without
  41  * generating an {@code IOException}.
  42  *
  43  * @author  Arthur van Hoff
  44  * @since   1.0
  45  */
  46 
  47 public class ByteArrayOutputStream extends OutputStream {
  48 
  49     /**
  50      * The buffer where data is stored.
  51      */
  52     protected byte buf[];
  53 
  54     /**
  55      * The number of valid bytes in the buffer.
  56      */
  57     protected int count;
  58 
  59     /**
  60      * Creates a new byte array output stream. The buffer capacity is
  61      * initially 32 bytes, though its size increases if necessary.
  62      */
  63     public ByteArrayOutputStream() {
  64         this(32);
  65     }
  66 
  67     /**
  68      * Creates a new byte array output stream, with a buffer capacity of
  69      * the specified size, in bytes.
  70      *
  71      * @param  size   the initial size.
  72      * @throws IllegalArgumentException if size is negative.
  73      */
  74     public ByteArrayOutputStream(int size) {
  75         if (size < 0) {
  76             throw new IllegalArgumentException("Negative initial size: "
  77                                                + size);
  78         }
  79         buf = new byte[size];
  80     }
  81 
  82     /**
  83      * Increases the capacity if necessary to ensure that it can hold
  84      * at least the number of elements specified by the minimum
  85      * capacity argument.
  86      *
  87      * @param  minCapacity the desired minimum capacity
  88      * @throws OutOfMemoryError if {@code minCapacity < 0}.  This is
  89      * interpreted as a request for the unsatisfiably large capacity
  90      * {@code (long) Integer.MAX_VALUE + (minCapacity - Integer.MAX_VALUE)}.
  91      */
  92     private void ensureCapacity(int minCapacity) {
  93         // overflow-conscious code
  94         if (minCapacity - buf.length > 0)
  95             grow(minCapacity);
  96     }
  97 
  98     /**
  99      * The maximum size of array to allocate.
 100      * Some VMs reserve some header words in an array.
 101      * Attempts to allocate larger arrays may result in
 102      * OutOfMemoryError: Requested array size exceeds VM limit
 103      */
 104     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 105 
 106     /**
 107      * Increases the capacity to ensure that it can hold at least the
 108      * number of elements specified by the minimum capacity argument.
 109      *
 110      * @param minCapacity the desired minimum capacity
 111      */
 112     private void grow(int minCapacity) {
 113         // overflow-conscious code
 114         int oldCapacity = buf.length;
 115         int newCapacity = oldCapacity << 1;
 116         if (newCapacity - minCapacity < 0)
 117             newCapacity = minCapacity;
 118         if (newCapacity - MAX_ARRAY_SIZE > 0)
 119             newCapacity = hugeCapacity(minCapacity);
 120         buf = Arrays.copyOf(buf, newCapacity);
 121     }
 122 
 123     private static int hugeCapacity(int minCapacity) {
 124         if (minCapacity < 0) // overflow
 125             throw new OutOfMemoryError();
 126         return (minCapacity > MAX_ARRAY_SIZE) ?
 127             Integer.MAX_VALUE :
 128             MAX_ARRAY_SIZE;
 129     }
 130 
 131     /**
 132      * Writes the specified byte to this byte array output stream.
 133      *
 134      * @param   b   the byte to be written.
 135      */
 136     public synchronized void write(int b) {
 137         ensureCapacity(count + 1);
 138         buf[count] = (byte) b;
 139         count += 1;
 140     }
 141 
 142     /**
 143      * Writes {@code len} bytes from the specified byte array
 144      * starting at offset {@code off} to this byte array output stream.
 145      *
 146      * @param   b     the data.
 147      * @param   off   the start offset in the data.
 148      * @param   len   the number of bytes to write.
 149      * @throws  NullPointerException if {@code b} is {@code null}.
 150      * @throws  IndexOutOfBoundsException if {@code off} is negative,
 151      * {@code len} is negative, or {@code len} is greater than
 152      * {@code b.length - off}
 153      */
 154     public synchronized void write(byte b[], int off, int len) {
 155         Objects.checkFromIndexSize(off, len, b.length);
 156         ensureCapacity(count + len);
 157         System.arraycopy(b, off, buf, count, len);
 158         count += len;
 159     }
 160 
 161     /**
 162      * Writes the complete contents of the specified byte array
 163      * to this byte array output stream.
 164      *
 165      * <p> This method is equivalent to {@link #write(byte[],int,int)
 166      * write(b,0,b.length)}.
 167      *
 168      * @param   b     the data.
 169      * @throws  NullPointerException if {@code b} is {@code null}.
 170      * @since   11
 171      */
 172     public void writeBytes(byte b[]) {
 173         write(b, 0, b.length);
 174     }
 175 
 176     /**
 177      * Writes the complete contents of this byte array output stream to
 178      * the specified output stream argument, as if by calling the output
 179      * stream's write method using {@code out.write(buf, 0, count)}.
 180      *
 181      * @param   out   the output stream to which to write the data.
 182      * @throws  NullPointerException if {@code out} is {@code null}.
 183      * @throws  IOException if an I/O error occurs.
 184      */
 185     public synchronized void writeTo(OutputStream out) throws IOException {
 186         out.write(buf, 0, count);
 187     }
 188 
 189     /**
 190      * Resets the {@code count} field of this byte array output
 191      * stream to zero, so that all currently accumulated output in the
 192      * output stream is discarded. The output stream can be used again,
 193      * reusing the already allocated buffer space.
 194      *
 195      * @see     java.io.ByteArrayInputStream#count
 196      */
 197     public synchronized void reset() {
 198         count = 0;
 199     }
 200 
 201     /**
 202      * Creates a newly allocated byte array. Its size is the current
 203      * size of this output stream and the valid contents of the buffer
 204      * have been copied into it.
 205      *
 206      * @return  the current contents of this output stream, as a byte array.
 207      * @see     java.io.ByteArrayOutputStream#size()
 208      */
 209     public synchronized byte[] toByteArray() {
 210         return Arrays.copyOf(buf, count);
 211     }
 212 
 213     /**
 214      * Returns the current size of the buffer.
 215      *
 216      * @return  the value of the {@code count} field, which is the number
 217      *          of valid bytes in this output stream.
 218      * @see     java.io.ByteArrayOutputStream#count
 219      */
 220     public synchronized int size() {
 221         return count;
 222     }
 223 
 224     /**
 225      * Converts the buffer's contents into a string decoding bytes using the
 226      * platform's default character set. The length of the new {@code String}
 227      * is a function of the character set, and hence may not be equal to the
 228      * size of the buffer.
 229      *
 230      * <p> This method always replaces malformed-input and unmappable-character
 231      * sequences with the default replacement string for the platform's
 232      * default character set. The {@linkplain java.nio.charset.CharsetDecoder}
 233      * class should be used when more control over the decoding process is
 234      * required.
 235      *
 236      * @return String decoded from the buffer's contents.
 237      * @since  1.1
 238      */
 239     public synchronized String toString() {
 240         return new String(buf, 0, count);
 241     }
 242 
 243     /**
 244      * Converts the buffer's contents into a string by decoding the bytes using
 245      * the named {@link java.nio.charset.Charset charset}.
 246      *
 247      * <p> This method is equivalent to {@code #toString(charset)} that takes a
 248      * {@link java.nio.charset.Charset charset}.
 249      *
 250      * <p> An invocation of this method of the form
 251      *
 252      * <pre> {@code
 253      *      ByteArrayOutputStream b = ...
 254      *      b.toString("UTF-8")
 255      *      }
 256      * </pre>
 257      *
 258      * behaves in exactly the same way as the expression
 259      *
 260      * <pre> {@code
 261      *      ByteArrayOutputStream b = ...
 262      *      b.toString(StandardCharsets.UTF_8)
 263      *      }
 264      * </pre>
 265      *
 266      *
 267      * @param  charsetName  the name of a supported
 268      *         {@link java.nio.charset.Charset charset}
 269      * @return String decoded from the buffer's contents.
 270      * @throws UnsupportedEncodingException
 271      *         If the named charset is not supported
 272      * @since  1.1
 273      */
 274     public synchronized String toString(String charsetName)
 275         throws UnsupportedEncodingException
 276     {
 277         return new String(buf, 0, count, charsetName);
 278     }
 279 
 280     /**
 281      * Converts the buffer's contents into a string by decoding the bytes using
 282      * the specified {@link java.nio.charset.Charset charset}. The length of the new
 283      * {@code String} is a function of the charset, and hence may not be equal
 284      * to the length of the byte array.
 285      *
 286      * <p> This method always replaces malformed-input and unmappable-character
 287      * sequences with the charset's default replacement string. The {@link
 288      * java.nio.charset.CharsetDecoder} class should be used when more control
 289      * over the decoding process is required.
 290      *
 291      * @param      charset  the {@linkplain java.nio.charset.Charset charset}
 292      *             to be used to decode the {@code bytes}
 293      * @return     String decoded from the buffer's contents.
 294      * @since      10
 295      */
 296     public synchronized String toString(Charset charset) {
 297         return new String(buf, 0, count, charset);
 298     }
 299 
 300     /**
 301      * Creates a newly allocated string. Its size is the current size of
 302      * the output stream and the valid contents of the buffer have been
 303      * copied into it. Each character <i>c</i> in the resulting string is
 304      * constructed from the corresponding element <i>b</i> in the byte
 305      * array such that:
 306      * <blockquote><pre>{@code
 307      *     c == (char)(((hibyte & 0xff) << 8) | (b & 0xff))
 308      * }</pre></blockquote>
 309      *
 310      * @deprecated This method does not properly convert bytes into characters.
 311      * As of JDK&nbsp;1.1, the preferred way to do this is via the
 312      * {@link #toString(String charsetName)} or {@link #toString(Charset charset)}
 313      * method, which takes an encoding-name or charset argument,
 314      * or the {@code toString()} method, which uses the platform's default
 315      * character encoding.
 316      *
 317      * @param      hibyte    the high byte of each resulting Unicode character.
 318      * @return     the current contents of the output stream, as a string.
 319      * @see        java.io.ByteArrayOutputStream#size()
 320      * @see        java.io.ByteArrayOutputStream#toString(String)
 321      * @see        java.io.ByteArrayOutputStream#toString()
 322      */
 323     @Deprecated
 324     public synchronized String toString(int hibyte) {
 325         return new String(buf, hibyte, 0, count);
 326     }
 327 
 328     /**
 329      * Closing a {@code ByteArrayOutputStream} has no effect. The methods in
 330      * this class can be called after the stream has been closed without
 331      * generating an {@code IOException}.
 332      */
 333     public void close() throws IOException {
 334     }
 335 
 336 }