1 /*
  2  * Copyright (c) 1994, 2024, 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 import jdk.internal.util.ArraysSupport;
 33 
 34 /**
 35  * This class implements an output stream in which the data is
 36  * written into a byte array. The buffer automatically grows as data
 37  * is written to it.
 38  * The data can be retrieved using {@code toByteArray()} and
 39  * {@code toString()}.
 40  * <p>
 41  * Closing a {@code ByteArrayOutputStream} has no effect. The methods in
 42  * this class can be called after the stream has been closed without
 43  * generating an {@code IOException}.
 44  *
 45  * @author  Arthur van Hoff
 46  * @since   1.0
 47  */
 48 
 49 public class ByteArrayOutputStream extends OutputStream {
 50 
 51     /**
 52      * The buffer where data is stored.
 53      */
 54     protected byte[] buf;
 55 
 56     /**
 57      * The number of valid bytes in the buffer.
 58      */
 59     protected int count;
 60 
 61     /**
 62      * Creates a new {@code ByteArrayOutputStream}. The buffer capacity is
 63      * initially 32 bytes, though its size increases if necessary.
 64      */
 65     public ByteArrayOutputStream() {
 66         this(32);
 67     }
 68 
 69     /**
 70      * Creates a new {@code ByteArrayOutputStream}, with a buffer capacity of
 71      * the specified size, in bytes.
 72      *
 73      * @param  size   the initial size.
 74      * @throws IllegalArgumentException if size is negative.
 75      */
 76     public ByteArrayOutputStream(int size) {
 77         if (size < 0) {
 78             throw new IllegalArgumentException("Negative initial size: "
 79                                                + size);
 80         }
 81         buf = new byte[size];
 82     }
 83 
 84     /**
 85      * Increases the capacity if necessary to ensure that it can hold
 86      * at least the number of elements specified by the minimum
 87      * capacity argument.
 88      *
 89      * @param  minCapacity the desired minimum capacity.
 90      * @throws OutOfMemoryError if {@code minCapacity < 0} and
 91      * {@code minCapacity - buf.length > 0}.  This is interpreted as a
 92      * request for the unsatisfiably large capacity.
 93      * {@code (long) Integer.MAX_VALUE + (minCapacity - Integer.MAX_VALUE)}.
 94      */
 95     private void ensureCapacity(int minCapacity) {
 96         // overflow-conscious code
 97         int oldCapacity = buf.length;
 98         int minGrowth = minCapacity - oldCapacity;
 99         if (minGrowth > 0) {
100             buf = Arrays.copyOf(buf, ArraysSupport.newLength(oldCapacity,
101                     minGrowth, oldCapacity /* preferred growth */));
102         }
103     }
104 
105     /**
106      * Writes the specified byte to this {@code ByteArrayOutputStream}.
107      *
108      * @param   b   the byte to be written.
109      */
110     @Override
111     public synchronized void write(int b) {
112         ensureCapacity(count + 1);
113         buf[count] = (byte) b;
114         count += 1;
115     }
116 
117     /**
118      * Writes {@code len} bytes from the specified byte array
119      * starting at offset {@code off} to this {@code ByteArrayOutputStream}.
120      *
121      * @param   b     {@inheritDoc}
122      * @param   off   {@inheritDoc}
123      * @param   len   {@inheritDoc}
124      * @throws  NullPointerException if {@code b} is {@code null}.
125      * @throws  IndexOutOfBoundsException if {@code off} is negative,
126      * {@code len} is negative, or {@code len} is greater than
127      * {@code b.length - off}
128      */
129     @Override
130     public synchronized void write(byte[] b, int off, int len) {
131         Objects.checkFromIndexSize(off, len, b.length);
132         ensureCapacity(count + len);
133         System.arraycopy(b, off, buf, count, len);
134         count += len;
135     }
136 
137     /**
138      * Writes the complete contents of the specified byte array
139      * to this {@code ByteArrayOutputStream}.
140      *
141      * @apiNote
142      * This method is equivalent to {@link #write(byte[],int,int)
143      * write(b, 0, b.length)}.
144      *
145      * @param   b     the data.
146      * @throws  NullPointerException if {@code b} is {@code null}.
147      * @since   11
148      */
149     public void writeBytes(byte[] b) {
150         write(b, 0, b.length);
151     }
152 
153     /**
154      * Writes the complete contents of this {@code ByteArrayOutputStream} to
155      * the specified output stream argument, as if by calling the output
156      * stream's write method using {@code out.write(buf, 0, count)}.
157      *
158      * @param   out   the output stream to which to write the data.
159      * @throws  NullPointerException if {@code out} is {@code null}.
160      * @throws  IOException if an I/O error occurs.
161      */
162     public synchronized void writeTo(OutputStream out) throws IOException {
163         out.write(buf, 0, count);
164     }
165 
166     /**
167      * Resets the {@code count} field of this {@code ByteArrayOutputStream}
168      * to zero, so that all currently accumulated output in the
169      * output stream is discarded. The output stream can be used again,
170      * reusing the already allocated buffer space.
171      *
172      * @see     java.io.ByteArrayInputStream#count
173      */
174     public synchronized void reset() {
175         count = 0;
176     }
177 
178     /**
179      * Creates a newly allocated byte array. Its size is the current
180      * size of this output stream and the valid contents of the buffer
181      * have been copied into it.
182      *
183      * @return  the current contents of this output stream, as a byte array.
184      * @see     java.io.ByteArrayOutputStream#size()
185      */
186     public synchronized byte[] toByteArray() {
187         return Arrays.copyOf(buf, count);
188     }
189 
190     /**
191      * Returns the current size of the buffer.
192      *
193      * @return  the value of the {@code count} field, which is the number
194      *          of valid bytes in this output stream.
195      * @see     java.io.ByteArrayOutputStream#count
196      */
197     public synchronized int size() {
198         return count;
199     }
200 
201     /**
202      * Converts the buffer's contents into a string decoding bytes using the
203      * default charset. The length of the new {@code String}
204      * is a function of the charset, and hence may not be equal to the
205      * size of the buffer.
206      *
207      * <p> This method always replaces malformed-input and unmappable-character
208      * sequences with the default replacement string for the
209      * default charset. The {@linkplain java.nio.charset.CharsetDecoder}
210      * class should be used when more control over the decoding process is
211      * required.
212      *
213      * @see Charset#defaultCharset()
214      * @return String decoded from the buffer's contents.
215      * @since  1.1
216      */
217     @Override
218     public synchronized String toString() {
219         return new String(buf, 0, count);
220     }
221 
222     /**
223      * Converts the buffer's contents into a string by decoding the bytes using
224      * the named {@link Charset charset}.
225      *
226      * <p> This method is equivalent to {@code #toString(charset)} that takes a
227      * {@link Charset charset}.
228      *
229      * <p> An invocation of this method of the form
230      *
231      * {@snippet lang=java :
232      *     ByteArrayOutputStream b;
233      *     b.toString("UTF-8")
234      * }
235      *
236      * behaves in exactly the same way as the expression
237      *
238      * {@snippet lang=java :
239      *     ByteArrayOutputStream b;
240      *     b.toString(StandardCharsets.UTF_8)
241      * }
242      *
243      *
244      * @param  charsetName  the name of a supported
245      *         {@link Charset charset}
246      * @return String decoded from the buffer's contents.
247      * @throws UnsupportedEncodingException
248      *         If the named charset is not supported
249      * @since  1.1
250      */
251     public synchronized String toString(String charsetName)
252         throws UnsupportedEncodingException
253     {
254         return new String(buf, 0, count, charsetName);
255     }
256 
257     /**
258      * Converts the buffer's contents into a string by decoding the bytes using
259      * the specified {@link Charset charset}. The length of the new
260      * {@code String} is a function of the charset, and hence may not be equal
261      * to the length of the byte array.
262      *
263      * <p> This method always replaces malformed-input and unmappable-character
264      * sequences with the charset's default replacement string. The {@link
265      * java.nio.charset.CharsetDecoder} class should be used when more control
266      * over the decoding process is required.
267      *
268      * @param      charset  the {@linkplain Charset charset}
269      *             to be used to decode the {@code bytes}
270      * @return     String decoded from the buffer's contents.
271      * @since      10
272      */
273     public synchronized String toString(Charset charset) {
274         return new String(buf, 0, count, charset);
275     }
276 
277     /**
278      * Creates a newly allocated string. Its size is the current size of
279      * the output stream and the valid contents of the buffer have been
280      * copied into it. Each character <i>c</i> in the resulting string is
281      * constructed from the corresponding element <i>b</i> in the byte
282      * array such that:
283      * {@snippet lang=java :
284      *     c == (char)(((hibyte & 0xff) << 8) | (b & 0xff))
285      * }
286      *
287      * @deprecated This method does not properly convert bytes into characters.
288      * As of JDK&nbsp;1.1, the preferred way to do this is via the
289      * {@link #toString(String charsetName)} or {@link #toString(Charset charset)}
290      * method, which takes an encoding-name or charset argument,
291      * or the {@code toString()} method, which uses the default charset.
292      *
293      * @param      hibyte    the high byte of each resulting Unicode character.
294      * @return     the current contents of the output stream, as a string.
295      * @see        java.io.ByteArrayOutputStream#size()
296      * @see        java.io.ByteArrayOutputStream#toString(String)
297      * @see        java.io.ByteArrayOutputStream#toString()
298      * @see        Charset#defaultCharset()
299      */
300     @Deprecated
301     public synchronized String toString(int hibyte) {
302         return new String(buf, hibyte, 0, count);
303     }
304 
305     /**
306      * Closing a {@code ByteArrayOutputStream} has no effect. The methods in
307      * this class can be called after the stream has been closed without
308      * generating an {@code IOException}.
309      */
310     @Override
311     public void close() throws IOException {
312     }
313 
314 }