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 {@code ByteArrayOutputStream}. The buffer capacity is 61 * initially 32 bytes, though its size increases if necessary. 62 */ ByteArrayOutputStream()63 public ByteArrayOutputStream() { 64 this(32); 65 } 66 67 /** 68 * Creates a new {@code ByteArrayOutputStream}, 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 */ ByteArrayOutputStream(int size)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 */ ensureCapacity(int minCapacity)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 */ grow(int minCapacity)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 hugeCapacity(int minCapacity)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 {@code ByteArrayOutputStream}. 133 * 134 * @param b the byte to be written. 135 */ write(int b)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 {@code ByteArrayOutputStream}. 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 */ write(byte b[], int off, int len)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 {@code ByteArrayOutputStream}. 164 * 165 * @apiNote 166 * This method is equivalent to {@link #write(byte[],int,int) 167 * write(b, 0, b.length)}. 168 * 169 * @param b the data. 170 * @throws NullPointerException if {@code b} is {@code null}. 171 * @since 11 172 */ writeBytes(byte b[])173 public void writeBytes(byte b[]) { 174 write(b, 0, b.length); 175 } 176 177 /** 178 * Writes the complete contents of this {@code ByteArrayOutputStream} to 179 * the specified output stream argument, as if by calling the output 180 * stream's write method using {@code out.write(buf, 0, count)}. 181 * 182 * @param out the output stream to which to write the data. 183 * @throws NullPointerException if {@code out} is {@code null}. 184 * @throws IOException if an I/O error occurs. 185 */ writeTo(OutputStream out)186 public synchronized void writeTo(OutputStream out) throws IOException { 187 out.write(buf, 0, count); 188 } 189 190 /** 191 * Resets the {@code count} field of this {@code ByteArrayOutputStream} 192 * to zero, so that all currently accumulated output in the 193 * output stream is discarded. The output stream can be used again, 194 * reusing the already allocated buffer space. 195 * 196 * @see java.io.ByteArrayInputStream#count 197 */ reset()198 public synchronized void reset() { 199 count = 0; 200 } 201 202 /** 203 * Creates a newly allocated byte array. Its size is the current 204 * size of this output stream and the valid contents of the buffer 205 * have been copied into it. 206 * 207 * @return the current contents of this output stream, as a byte array. 208 * @see java.io.ByteArrayOutputStream#size() 209 */ toByteArray()210 public synchronized byte[] toByteArray() { 211 return Arrays.copyOf(buf, count); 212 } 213 214 /** 215 * Returns the current size of the buffer. 216 * 217 * @return the value of the {@code count} field, which is the number 218 * of valid bytes in this output stream. 219 * @see java.io.ByteArrayOutputStream#count 220 */ size()221 public synchronized int size() { 222 return count; 223 } 224 225 /** 226 * Converts the buffer's contents into a string decoding bytes using the 227 * platform's default character set. The length of the new {@code String} 228 * is a function of the character set, and hence may not be equal to the 229 * size of the buffer. 230 * 231 * <p> This method always replaces malformed-input and unmappable-character 232 * sequences with the default replacement string for the platform's 233 * default character set. The {@linkplain java.nio.charset.CharsetDecoder} 234 * class should be used when more control over the decoding process is 235 * required. 236 * 237 * @return String decoded from the buffer's contents. 238 * @since 1.1 239 */ toString()240 public synchronized String toString() { 241 return new String(buf, 0, count); 242 } 243 244 /** 245 * Converts the buffer's contents into a string by decoding the bytes using 246 * the named {@link java.nio.charset.Charset charset}. 247 * 248 * <p> This method is equivalent to {@code #toString(charset)} that takes a 249 * {@link java.nio.charset.Charset charset}. 250 * 251 * <p> An invocation of this method of the form 252 * 253 * <pre> {@code 254 * ByteArrayOutputStream b = ... 255 * b.toString("UTF-8") 256 * } 257 * </pre> 258 * 259 * behaves in exactly the same way as the expression 260 * 261 * <pre> {@code 262 * ByteArrayOutputStream b = ... 263 * b.toString(StandardCharsets.UTF_8) 264 * } 265 * </pre> 266 * 267 * 268 * @param charsetName the name of a supported 269 * {@link java.nio.charset.Charset charset} 270 * @return String decoded from the buffer's contents. 271 * @throws UnsupportedEncodingException 272 * If the named charset is not supported 273 * @since 1.1 274 */ toString(String charsetName)275 public synchronized String toString(String charsetName) 276 throws UnsupportedEncodingException 277 { 278 return new String(buf, 0, count, charsetName); 279 } 280 281 /** 282 * Converts the buffer's contents into a string by decoding the bytes using 283 * the specified {@link java.nio.charset.Charset charset}. The length of the new 284 * {@code String} is a function of the charset, and hence may not be equal 285 * to the length of the byte array. 286 * 287 * <p> This method always replaces malformed-input and unmappable-character 288 * sequences with the charset's default replacement string. The {@link 289 * java.nio.charset.CharsetDecoder} class should be used when more control 290 * over the decoding process is required. 291 * 292 * @param charset the {@linkplain java.nio.charset.Charset charset} 293 * to be used to decode the {@code bytes} 294 * @return String decoded from the buffer's contents. 295 * @since 10 296 */ toString(Charset charset)297 public synchronized String toString(Charset charset) { 298 return new String(buf, 0, count, charset); 299 } 300 301 /** 302 * Creates a newly allocated string. Its size is the current size of 303 * the output stream and the valid contents of the buffer have been 304 * copied into it. Each character <i>c</i> in the resulting string is 305 * constructed from the corresponding element <i>b</i> in the byte 306 * array such that: 307 * <blockquote><pre>{@code 308 * c == (char)(((hibyte & 0xff) << 8) | (b & 0xff)) 309 * }</pre></blockquote> 310 * 311 * @deprecated This method does not properly convert bytes into characters. 312 * As of JDK 1.1, the preferred way to do this is via the 313 * {@link #toString(String charsetName)} or {@link #toString(Charset charset)} 314 * method, which takes an encoding-name or charset argument, 315 * or the {@code toString()} method, which uses the platform's default 316 * character encoding. 317 * 318 * @param hibyte the high byte of each resulting Unicode character. 319 * @return the current contents of the output stream, as a string. 320 * @see java.io.ByteArrayOutputStream#size() 321 * @see java.io.ByteArrayOutputStream#toString(String) 322 * @see java.io.ByteArrayOutputStream#toString() 323 */ 324 @Deprecated toString(int hibyte)325 public synchronized String toString(int hibyte) { 326 return new String(buf, hibyte, 0, count); 327 } 328 329 /** 330 * Closing a {@code ByteArrayOutputStream} has no effect. The methods in 331 * this class can be called after the stream has been closed without 332 * generating an {@code IOException}. 333 */ close()334 public void close() throws IOException { 335 } 336 337 } 338