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