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