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