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