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.util.ArrayList; 29 import java.util.Arrays; 30 import java.util.Objects; 31 32 /** 33 * This abstract class is the superclass of all classes representing 34 * an input stream of bytes. 35 * 36 * <p> Applications that need to define a subclass of <code>InputStream</code> 37 * must always provide a method that returns the next byte of input. 38 * 39 * @author Arthur van Hoff 40 * @see java.io.BufferedInputStream 41 * @see java.io.ByteArrayInputStream 42 * @see java.io.DataInputStream 43 * @see java.io.FilterInputStream 44 * @see java.io.InputStream#read() 45 * @see java.io.OutputStream 46 * @see java.io.PushbackInputStream 47 * @since 1.0 48 */ 49 public abstract class InputStream implements Closeable { 50 51 // MAX_SKIP_BUFFER_SIZE is used to determine the maximum buffer size to 52 // use when skipping. 53 private static final int MAX_SKIP_BUFFER_SIZE = 2048; 54 55 private static final int DEFAULT_BUFFER_SIZE = 8192; 56 57 /** 58 * Reads the next byte of data from the input stream. The value byte is 59 * returned as an <code>int</code> in the range <code>0</code> to 60 * <code>255</code>. If no byte is available because the end of the stream 61 * has been reached, the value <code>-1</code> is returned. This method 62 * blocks until input data is available, the end of the stream is detected, 63 * or an exception is thrown. 64 * 65 * <p> A subclass must provide an implementation of this method. 66 * 67 * @return the next byte of data, or <code>-1</code> if the end of the 68 * stream is reached. 69 * @exception IOException if an I/O error occurs. 70 */ 71 public abstract int read() throws IOException; 72 73 /** 74 * Reads some number of bytes from the input stream and stores them into 75 * the buffer array <code>b</code>. The number of bytes actually read is 76 * returned as an integer. This method blocks until input data is 77 * available, end of file is detected, or an exception is thrown. 78 * 79 * <p> If the length of <code>b</code> is zero, then no bytes are read and 80 * <code>0</code> is returned; otherwise, there is an attempt to read at 81 * least one byte. If no byte is available because the stream is at the 82 * end of the file, the value <code>-1</code> is returned; otherwise, at 83 * least one byte is read and stored into <code>b</code>. 84 * 85 * <p> The first byte read is stored into element <code>b[0]</code>, the 86 * next one into <code>b[1]</code>, and so on. The number of bytes read is, 87 * at most, equal to the length of <code>b</code>. Let <i>k</i> be the 88 * number of bytes actually read; these bytes will be stored in elements 89 * <code>b[0]</code> through <code>b[</code><i>k</i><code>-1]</code>, 90 * leaving elements <code>b[</code><i>k</i><code>]</code> through 91 * <code>b[b.length-1]</code> unaffected. 92 * 93 * <p> The <code>read(b)</code> method for class <code>InputStream</code> 94 * has the same effect as: <pre><code> read(b, 0, b.length) </code></pre> 95 * 96 * @param b the buffer into which the data is read. 97 * @return the total number of bytes read into the buffer, or 98 * <code>-1</code> if there is no more data because the end of 99 * the stream has been reached. 100 * @exception IOException If the first byte cannot be read for any reason 101 * other than the end of the file, if the input stream has been closed, or 102 * if some other I/O error occurs. 103 * @exception NullPointerException if <code>b</code> is <code>null</code>. 104 * @see java.io.InputStream#read(byte[], int, int) 105 */ 106 public int read(byte b[]) throws IOException { 107 return read(b, 0, b.length); 108 } 109 110 /** 111 * Reads up to <code>len</code> bytes of data from the input stream into 112 * an array of bytes. An attempt is made to read as many as 113 * <code>len</code> bytes, but a smaller number may be read. 114 * The number of bytes actually read is returned as an integer. 115 * 116 * <p> This method blocks until input data is available, end of file is 117 * detected, or an exception is thrown. 118 * 119 * <p> If <code>len</code> is zero, then no bytes are read and 120 * <code>0</code> is returned; otherwise, there is an attempt to read at 121 * least one byte. If no byte is available because the stream is at end of 122 * file, the value <code>-1</code> is returned; otherwise, at least one 123 * byte is read and stored into <code>b</code>. 124 * 125 * <p> The first byte read is stored into element <code>b[off]</code>, the 126 * next one into <code>b[off+1]</code>, and so on. The number of bytes read 127 * is, at most, equal to <code>len</code>. Let <i>k</i> be the number of 128 * bytes actually read; these bytes will be stored in elements 129 * <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>, 130 * leaving elements <code>b[off+</code><i>k</i><code>]</code> through 131 * <code>b[off+len-1]</code> unaffected. 132 * 133 * <p> In every case, elements <code>b[0]</code> through 134 * <code>b[off]</code> and elements <code>b[off+len]</code> through 135 * <code>b[b.length-1]</code> are unaffected. 136 * 137 * <p> The <code>read(b,</code> <code>off,</code> <code>len)</code> method 138 * for class <code>InputStream</code> simply calls the method 139 * <code>read()</code> repeatedly. If the first such call results in an 140 * <code>IOException</code>, that exception is returned from the call to 141 * the <code>read(b,</code> <code>off,</code> <code>len)</code> method. If 142 * any subsequent call to <code>read()</code> results in a 143 * <code>IOException</code>, the exception is caught and treated as if it 144 * were end of file; the bytes read up to that point are stored into 145 * <code>b</code> and the number of bytes read before the exception 146 * occurred is returned. The default implementation of this method blocks 147 * until the requested amount of input data <code>len</code> has been read, 148 * end of file is detected, or an exception is thrown. Subclasses are encouraged 149 * to provide a more efficient implementation of this method. 150 * 151 * @param b the buffer into which the data is read. 152 * @param off the start offset in array <code>b</code> 153 * at which the data is written. 154 * @param len the maximum number of bytes to read. 155 * @return the total number of bytes read into the buffer, or 156 * <code>-1</code> if there is no more data because the end of 157 * the stream has been reached. 158 * @exception IOException If the first byte cannot be read for any reason 159 * other than end of file, or if the input stream has been closed, or if 160 * some other I/O error occurs. 161 * @exception NullPointerException If <code>b</code> is <code>null</code>. 162 * @exception IndexOutOfBoundsException If <code>off</code> is negative, 163 * <code>len</code> is negative, or <code>len</code> is greater than 164 * <code>b.length - off</code> 165 * @see java.io.InputStream#read() 166 */ 167 public int read(byte b[], int off, int len) throws IOException { 168 Objects.requireNonNull(b); 169 Objects.checkFromIndexSize(off, len, b.length); 170 if (len == 0) { 171 return 0; 172 } 173 174 int c = read(); 175 if (c == -1) { 176 return -1; 177 } 178 b[off] = (byte)c; 179 180 int i = 1; 181 try { 182 for (; i < len ; i++) { 183 c = read(); 184 if (c == -1) { 185 break; 186 } 187 b[off + i] = (byte)c; 188 } 189 } catch (IOException ee) { 190 } 191 return i; 192 } 193 194 /** 195 * The maximum size of array to allocate. 196 * Some VMs reserve some header words in an array. 197 * Attempts to allocate larger arrays may result in 198 * OutOfMemoryError: Requested array size exceeds VM limit 199 */ 200 private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8; 201 202 /** 203 * Reads all remaining bytes from the input stream. This method blocks until 204 * all remaining bytes have been read and end of stream is detected, or an 205 * exception is thrown. This method does not close the input stream. 206 * 207 * <p> When this stream reaches end of stream, further invocations of this 208 * method will return an empty byte array. 209 * 210 * <p> Note that this method is intended for simple cases where it is 211 * convenient to read all bytes into a byte array. It is not intended for 212 * reading input streams with large amounts of data. 213 * 214 * <p> The behavior for the case where the input stream is <i>asynchronously 215 * closed</i>, or the thread interrupted during the read, is highly input 216 * stream specific, and therefore not specified. 217 * 218 * <p> If an I/O error occurs reading from the input stream, then it may do 219 * so after some, but not all, bytes have been read. Consequently the input 220 * stream may not be at end of stream and may be in an inconsistent state. 221 * It is strongly recommended that the stream be promptly closed if an I/O 222 * error occurs. 223 * 224 * @return a byte array containing the bytes read from this input stream 225 * @throws IOException if an I/O error occurs 226 * @throws OutOfMemoryError if an array of the required size cannot be 227 * allocated. For example, if an array larger than {@code 2GB} would 228 * be required to store the bytes. 229 * 230 * @since 9 231 */ 232 public byte[] readAllBytes() throws IOException { 233 var bufs = new ArrayList<byte[]>(8); 234 var buf = new byte[DEFAULT_BUFFER_SIZE]; 235 int total = 0; 236 int n; 237 do { 238 int nread = 0; 239 240 // read to EOF which may read more or less than buffer size 241 while ((n = read(buf, nread, buf.length - nread)) > 0) { 242 nread += n; 243 } 244 245 if (nread > 0) { 246 if (MAX_BUFFER_SIZE - total < nread) { 247 throw new OutOfMemoryError("Required array size too large"); 248 } 249 total += nread; 250 var copy = (n < 0 && nread == DEFAULT_BUFFER_SIZE) ? 251 buf : Arrays.copyOf(buf, nread); 252 bufs.add(copy); 253 } 254 } while (n >= 0); // if the last call to read returned -1, then break 255 256 if (bufs.size() == 1) { 257 return bufs.get(0); 258 } 259 260 var result = new byte[total]; 261 int offset = 0; 262 for (var b : bufs) { 263 System.arraycopy(b, 0, result, offset, b.length); 264 offset += b.length; 265 } 266 267 return result; 268 } 269 270 /** 271 * Reads the requested number of bytes from the input stream into the given 272 * byte array. This method blocks until {@code len} bytes of input data have 273 * been read, end of stream is detected, or an exception is thrown. The 274 * number of bytes actually read, possibly zero, is returned. This method 275 * does not close the input stream. 276 * 277 * <p> In the case where end of stream is reached before {@code len} bytes 278 * have been read, then the actual number of bytes read will be returned. 279 * When this stream reaches end of stream, further invocations of this 280 * method will return zero. 281 * 282 * <p> If {@code len} is zero, then no bytes are read and {@code 0} is 283 * returned; otherwise, there is an attempt to read up to {@code len} bytes. 284 * 285 * <p> The first byte read is stored into element {@code b[off]}, the next 286 * one in to {@code b[off+1]}, and so on. The number of bytes read is, at 287 * most, equal to {@code len}. Let <i>k</i> be the number of bytes actually 288 * read; these bytes will be stored in elements {@code b[off]} through 289 * {@code b[off+}<i>k</i>{@code -1]}, leaving elements {@code b[off+}<i>k</i> 290 * {@code ]} through {@code b[off+len-1]} unaffected. 291 * 292 * <p> The behavior for the case where the input stream is <i>asynchronously 293 * closed</i>, or the thread interrupted during the read, is highly input 294 * stream specific, and therefore not specified. 295 * 296 * <p> If an I/O error occurs reading from the input stream, then it may do 297 * so after some, but not all, bytes of {@code b} have been updated with 298 * data from the input stream. Consequently the input stream and {@code b} 299 * may be in an inconsistent state. It is strongly recommended that the 300 * stream be promptly closed if an I/O error occurs. 301 * 302 * @param b the byte array into which the data is read 303 * @param off the start offset in {@code b} at which the data is written 304 * @param len the maximum number of bytes to read 305 * @return the actual number of bytes read into the buffer 306 * @throws IOException if an I/O error occurs 307 * @throws NullPointerException if {@code b} is {@code null} 308 * @throws IndexOutOfBoundsException If {@code off} is negative, {@code len} 309 * is negative, or {@code len} is greater than {@code b.length - off} 310 * 311 * @since 9 312 */ 313 public int readNBytes(byte[] b, int off, int len) throws IOException { 314 Objects.requireNonNull(b); 315 Objects.checkFromIndexSize(off, len, b.length); 316 317 int n = 0; 318 while (n < len) { 319 int count = read(b, off + n, len - n); 320 if (count < 0) 321 break; 322 n += count; 323 } 324 return n; 325 } 326 327 /** 328 * Skips over and discards <code>n</code> bytes of data from this input 329 * stream. The <code>skip</code> method may, for a variety of reasons, end 330 * up skipping over some smaller number of bytes, possibly <code>0</code>. 331 * This may result from any of a number of conditions; reaching end of file 332 * before <code>n</code> bytes have been skipped is only one possibility. 333 * The actual number of bytes skipped is returned. If {@code n} is 334 * negative, the {@code skip} method for class {@code InputStream} always 335 * returns 0, and no bytes are skipped. Subclasses may handle the negative 336 * value differently. 337 * 338 * <p> The <code>skip</code> method implementation of this class creates a 339 * byte array and then repeatedly reads into it until <code>n</code> bytes 340 * have been read or the end of the stream has been reached. Subclasses are 341 * encouraged to provide a more efficient implementation of this method. 342 * For instance, the implementation may depend on the ability to seek. 343 * 344 * @param n the number of bytes to be skipped. 345 * @return the actual number of bytes skipped. 346 * @throws IOException if an I/O error occurs. 347 */ 348 public long skip(long n) throws IOException { 349 350 long remaining = n; 351 int nr; 352 353 if (n <= 0) { 354 return 0; 355 } 356 357 int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining); 358 byte[] skipBuffer = new byte[size]; 359 while (remaining > 0) { 360 nr = read(skipBuffer, 0, (int)Math.min(size, remaining)); 361 if (nr < 0) { 362 break; 363 } 364 remaining -= nr; 365 } 366 367 return n - remaining; 368 } 369 370 /** 371 * Returns an estimate of the number of bytes that can be read (or 372 * skipped over) from this input stream without blocking by the next 373 * invocation of a method for this input stream. The next invocation 374 * might be the same thread or another thread. A single read or skip of this 375 * many bytes will not block, but may read or skip fewer bytes. 376 * 377 * <p> Note that while some implementations of {@code InputStream} will return 378 * the total number of bytes in the stream, many will not. It is 379 * never correct to use the return value of this method to allocate 380 * a buffer intended to hold all data in this stream. 381 * 382 * <p> A subclass' implementation of this method may choose to throw an 383 * {@link IOException} if this input stream has been closed by 384 * invoking the {@link #close()} method. 385 * 386 * <p> The {@code available} method for class {@code InputStream} always 387 * returns {@code 0}. 388 * 389 * <p> This method should be overridden by subclasses. 390 * 391 * @return an estimate of the number of bytes that can be read (or skipped 392 * over) from this input stream without blocking or {@code 0} when 393 * it reaches the end of the input stream. 394 * @exception IOException if an I/O error occurs. 395 */ 396 public int available() throws IOException { 397 return 0; 398 } 399 400 /** 401 * Closes this input stream and releases any system resources associated 402 * with the stream. 403 * 404 * <p> The <code>close</code> method of <code>InputStream</code> does 405 * nothing. 406 * 407 * @exception IOException if an I/O error occurs. 408 */ 409 public void close() throws IOException {} 410 411 /** 412 * Marks the current position in this input stream. A subsequent call to 413 * the <code>reset</code> method repositions this stream at the last marked 414 * position so that subsequent reads re-read the same bytes. 415 * 416 * <p> The <code>readlimit</code> arguments tells this input stream to 417 * allow that many bytes to be read before the mark position gets 418 * invalidated. 419 * 420 * <p> The general contract of <code>mark</code> is that, if the method 421 * <code>markSupported</code> returns <code>true</code>, the stream somehow 422 * remembers all the bytes read after the call to <code>mark</code> and 423 * stands ready to supply those same bytes again if and whenever the method 424 * <code>reset</code> is called. However, the stream is not required to 425 * remember any data at all if more than <code>readlimit</code> bytes are 426 * read from the stream before <code>reset</code> is called. 427 * 428 * <p> Marking a closed stream should not have any effect on the stream. 429 * 430 * <p> The <code>mark</code> method of <code>InputStream</code> does 431 * nothing. 432 * 433 * @param readlimit the maximum limit of bytes that can be read before 434 * the mark position becomes invalid. 435 * @see java.io.InputStream#reset() 436 */ 437 public synchronized void mark(int readlimit) {} 438 439 /** 440 * Repositions this stream to the position at the time the 441 * <code>mark</code> method was last called on this input stream. 442 * 443 * <p> The general contract of <code>reset</code> is: 444 * 445 * <ul> 446 * <li> If the method <code>markSupported</code> returns 447 * <code>true</code>, then: 448 * 449 * <ul><li> If the method <code>mark</code> has not been called since 450 * the stream was created, or the number of bytes read from the stream 451 * since <code>mark</code> was last called is larger than the argument 452 * to <code>mark</code> at that last call, then an 453 * <code>IOException</code> might be thrown. 454 * 455 * <li> If such an <code>IOException</code> is not thrown, then the 456 * stream is reset to a state such that all the bytes read since the 457 * most recent call to <code>mark</code> (or since the start of the 458 * file, if <code>mark</code> has not been called) will be resupplied 459 * to subsequent callers of the <code>read</code> method, followed by 460 * any bytes that otherwise would have been the next input data as of 461 * the time of the call to <code>reset</code>. </ul> 462 * 463 * <li> If the method <code>markSupported</code> returns 464 * <code>false</code>, then: 465 * 466 * <ul><li> The call to <code>reset</code> may throw an 467 * <code>IOException</code>. 468 * 469 * <li> If an <code>IOException</code> is not thrown, then the stream 470 * is reset to a fixed state that depends on the particular type of the 471 * input stream and how it was created. The bytes that will be supplied 472 * to subsequent callers of the <code>read</code> method depend on the 473 * particular type of the input stream. </ul></ul> 474 * 475 * <p>The method <code>reset</code> for class <code>InputStream</code> 476 * does nothing except throw an <code>IOException</code>. 477 * 478 * @exception IOException if this stream has not been marked or if the 479 * mark has been invalidated. 480 * @see java.io.InputStream#mark(int) 481 * @see java.io.IOException 482 */ 483 public synchronized void reset() throws IOException { 484 throw new IOException("mark/reset not supported"); 485 } 486 487 /** 488 * Tests if this input stream supports the <code>mark</code> and 489 * <code>reset</code> methods. Whether or not <code>mark</code> and 490 * <code>reset</code> are supported is an invariant property of a 491 * particular input stream instance. The <code>markSupported</code> method 492 * of <code>InputStream</code> returns <code>false</code>. 493 * 494 * @return <code>true</code> if this stream instance supports the mark 495 * and reset methods; <code>false</code> otherwise. 496 * @see java.io.InputStream#mark(int) 497 * @see java.io.InputStream#reset() 498 */ 499 public boolean markSupported() { 500 return false; 501 } 502 503 /** 504 * Reads all bytes from this input stream and writes the bytes to the 505 * given output stream in the order that they are read. On return, this 506 * input stream will be at end of stream. This method does not close either 507 * stream. 508 * <p> 509 * This method may block indefinitely reading from the input stream, or 510 * writing to the output stream. The behavior for the case where the input 511 * and/or output stream is <i>asynchronously closed</i>, or the thread 512 * interrupted during the transfer, is highly input and output stream 513 * specific, and therefore not specified. 514 * <p> 515 * If an I/O error occurs reading from the input stream or writing to the 516 * output stream, then it may do so after some bytes have been read or 517 * written. Consequently the input stream may not be at end of stream and 518 * one, or both, streams may be in an inconsistent state. It is strongly 519 * recommended that both streams be promptly closed if an I/O error occurs. 520 * 521 * @param out the output stream, non-null 522 * @return the number of bytes transferred 523 * @throws IOException if an I/O error occurs when reading or writing 524 * @throws NullPointerException if {@code out} is {@code null} 525 * 526 * @since 9 527 */ 528 public long transferTo(OutputStream out) throws IOException { 529 Objects.requireNonNull(out, "out"); 530 long transferred = 0; 531 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 532 int read; 533 while ((read = this.read(buffer, 0, DEFAULT_BUFFER_SIZE)) >= 0) { 534 out.write(buffer, 0, read); 535 transferred += read; 536 } 537 return transferred; 538 } 539 }