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