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