src/java.base/share/classes/java/io/InputStream.java

Print this page




   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.Objects;
  29 
  30 /**
  31  * This abstract class is the superclass of all classes representing
  32  * an input stream of bytes.
  33  *
  34  * <p> Applications that need to define a subclass of <code>InputStream</code>
  35  * must always provide a method that returns the next byte of input.
  36  *
  37  * @author  Arthur van Hoff
  38  * @see     java.io.BufferedInputStream
  39  * @see     java.io.ByteArrayInputStream
  40  * @see     java.io.DataInputStream
  41  * @see     java.io.FilterInputStream
  42  * @see     java.io.InputStream#read()
  43  * @see     java.io.OutputStream
  44  * @see     java.io.PushbackInputStream
  45  * @since   1.0
  46  */
  47 public abstract class InputStream implements Closeable {
  48 
  49     // MAX_SKIP_BUFFER_SIZE is used to determine the maximum buffer size to
  50     // use when skipping.
  51     private static final int MAX_SKIP_BUFFER_SIZE = 2048;
  52 
  53     private static final int TRANSFER_BUFFER_SIZE = 8192;
  54 
  55     /**
  56      * Reads the next byte of data from the input stream. The value byte is
  57      * returned as an <code>int</code> in the range <code>0</code> to
  58      * <code>255</code>. If no byte is available because the end of the stream
  59      * has been reached, the value <code>-1</code> is returned. This method
  60      * blocks until input data is available, the end of the stream is detected,
  61      * or an exception is thrown.
  62      *
  63      * <p> A subclass must provide an implementation of this method.
  64      *
  65      * @return     the next byte of data, or <code>-1</code> if the end of the
  66      *             stream is reached.
  67      * @exception  IOException  if an I/O error occurs.
  68      */
  69     public abstract int read() throws IOException;
  70 
  71     /**
  72      * Reads some number of bytes from the input stream and stores them into
  73      * the buffer array <code>b</code>. The number of bytes actually read is


 175         if (c == -1) {
 176             return -1;
 177         }
 178         b[off] = (byte)c;
 179 
 180         int i = 1;
 181         try {
 182             for (; i < len ; i++) {
 183                 c = read();
 184                 if (c == -1) {
 185                     break;
 186                 }
 187                 b[off + i] = (byte)c;
 188             }
 189         } catch (IOException ee) {
 190         }
 191         return i;
 192     }
 193 
 194     /**






























































































































 195      * Skips over and discards <code>n</code> bytes of data from this input
 196      * stream. The <code>skip</code> method may, for a variety of reasons, end
 197      * up skipping over some smaller number of bytes, possibly <code>0</code>.
 198      * This may result from any of a number of conditions; reaching end of file
 199      * before <code>n</code> bytes have been skipped is only one possibility.
 200      * The actual number of bytes skipped is returned. If {@code n} is
 201      * negative, the {@code skip} method for class {@code InputStream} always
 202      * returns 0, and no bytes are skipped. Subclasses may handle the negative
 203      * value differently.
 204      *
 205      * <p> The <code>skip</code> method of this class creates a
 206      * byte array and then repeatedly reads into it until <code>n</code> bytes
 207      * have been read or the end of the stream has been reached. Subclasses are
 208      * encouraged to provide a more efficient implementation of this method.
 209      * For instance, the implementation may depend on the ability to seek.
 210      *
 211      * @param      n   the number of bytes to be skipped.
 212      * @return     the actual number of bytes skipped.
 213      * @exception  IOException  if the stream does not support seek,
 214      *                          or if some other I/O error occurs.


 379      * and/or output stream is <i>asynchronously closed</i>, or the thread
 380      * interrupted during the transfer, is highly input and output stream
 381      * specific, and therefore not specified.
 382      * <p>
 383      * If an I/O error occurs reading from the input stream or writing to the
 384      * output stream, then it may do so after some bytes have been read or
 385      * written. Consequently the input stream may not be at end of stream and
 386      * one, or both, streams may be in an inconsistent state. It is strongly
 387      * recommended that both streams be promptly closed if an I/O error occurs.
 388      *
 389      * @param  out the output stream, non-null
 390      * @return the number of bytes transferred
 391      * @throws IOException if an I/O error occurs when reading or writing
 392      * @throws NullPointerException if {@code out} is {@code null}
 393      *
 394      * @since 1.9
 395      */
 396     public long transferTo(OutputStream out) throws IOException {
 397         Objects.requireNonNull(out, "out");
 398         long transferred = 0;
 399         byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
 400         int read;
 401         while ((read = this.read(buffer, 0, TRANSFER_BUFFER_SIZE)) >= 0) {
 402             out.write(buffer, 0, read);
 403             transferred += read;
 404         }
 405         return transferred;
 406     }
 407 }


   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


 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.


 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 }