< prev index next >

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

Print this page




  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      * Returns a new {@code InputStream} that reads no bytes. The returned
  60      * stream is initially open.  The stream is closed by calling the
  61      * {@code close()} method.  Subsequent calls to {@code close()} have no
  62      * effect.
  63      *
  64      * <p> While the stream is open, the {@code available()}, {@code read()},
  65      * {@code read(byte[])}, {@code read(byte[], int, int)},
  66      * {@code readAllBytes()}, {@code readNBytes()}, {@code skip()}, and

  67      * {@code transferTo()} methods all behave as if end of stream has been
  68      * reached.  After the stream has been closed, these methods all throw
  69      * {@code IOException}.
  70      *
  71      * <p> The {@code markSupported()} method returns {@code false}.  The
  72      * {@code mark()} method does nothing, and the {@code reset()} method
  73      * throws {@code IOException}.
  74      *
  75      * @return an {@code InputStream} which contains no bytes
  76      *
  77      * @since 11
  78      */
  79     public static InputStream nullInputStream() {
  80         return new InputStream() {
  81             private volatile boolean closed;
  82 
  83             private void ensureOpen() throws IOException {
  84                 if (closed) {
  85                     throw new IOException("Stream closed");
  86                 }


 106                 }
 107                 ensureOpen();
 108                 return -1;
 109             }
 110 
 111             @Override
 112             public byte[] readAllBytes() throws IOException {
 113                 ensureOpen();
 114                 return new byte[0];
 115             }
 116 
 117             @Override
 118             public int readNBytes(byte[] b, int off, int len)
 119                 throws IOException {
 120                 Objects.checkFromIndexSize(off, len, b.length);
 121                 ensureOpen();
 122                 return 0;
 123             }
 124 
 125             @Override









 126             public long skip(long n) throws IOException {
 127                 ensureOpen();
 128                 return 0L;
 129             }
 130 
 131             @Override
 132             public long transferTo(OutputStream out) throws IOException {
 133                 Objects.requireNonNull(out);
 134                 ensureOpen();
 135                 return 0L;
 136             }
 137 
 138             @Override
 139             public void close() throws IOException {
 140                 closed = true;
 141             }
 142         };
 143     }
 144 
 145     /**


 216      * bytes actually read; these bytes will be stored in elements
 217      * <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>,
 218      * leaving elements <code>b[off+</code><i>k</i><code>]</code> through
 219      * <code>b[off+len-1]</code> unaffected.
 220      *
 221      * <p> In every case, elements <code>b[0]</code> through
 222      * <code>b[off]</code> and elements <code>b[off+len]</code> through
 223      * <code>b[b.length-1]</code> are unaffected.
 224      *
 225      * <p> The <code>read(b,</code> <code>off,</code> <code>len)</code> method
 226      * for class <code>InputStream</code> simply calls the method
 227      * <code>read()</code> repeatedly. If the first such call results in an
 228      * <code>IOException</code>, that exception is returned from the call to
 229      * the <code>read(b,</code> <code>off,</code> <code>len)</code> method.  If
 230      * any subsequent call to <code>read()</code> results in a
 231      * <code>IOException</code>, the exception is caught and treated as if it
 232      * were end of file; the bytes read up to that point are stored into
 233      * <code>b</code> and the number of bytes read before the exception
 234      * occurred is returned. The default implementation of this method blocks
 235      * until the requested amount of input data <code>len</code> has been read,
 236      * end of file is detected, or an exception is thrown. Subclasses are encouraged
 237      * to provide a more efficient implementation of this method.
 238      *
 239      * @param      b     the buffer into which the data is read.
 240      * @param      off   the start offset in array <code>b</code>
 241      *                   at which the data is written.
 242      * @param      len   the maximum number of bytes to read.
 243      * @return     the total number of bytes read into the buffer, or
 244      *             <code>-1</code> if there is no more data because the end of
 245      *             the stream has been reached.
 246      * @exception  IOException If the first byte cannot be read for any reason
 247      * other than end of file, or if the input stream has been closed, or if
 248      * some other I/O error occurs.
 249      * @exception  NullPointerException If <code>b</code> is <code>null</code>.
 250      * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
 251      * <code>len</code> is negative, or <code>len</code> is greater than
 252      * <code>b.length - off</code>
 253      * @see        java.io.InputStream#read()
 254      */
 255     public int read(byte b[], int off, int len) throws IOException {
 256         Objects.checkFromIndexSize(off, len, b.length);
 257         if (len == 0) {


 291      * all remaining bytes have been read and end of stream is detected, or an
 292      * exception is thrown. This method does not close the input stream.
 293      *
 294      * <p> When this stream reaches end of stream, further invocations of this
 295      * method will return an empty byte array.
 296      *
 297      * <p> Note that this method is intended for simple cases where it is
 298      * convenient to read all bytes into a byte array. It is not intended for
 299      * reading input streams with large amounts of data.
 300      *
 301      * <p> The behavior for the case where the input stream is <i>asynchronously
 302      * closed</i>, or the thread interrupted during the read, is highly input
 303      * stream specific, and therefore not specified.
 304      *
 305      * <p> If an I/O error occurs reading from the input stream, then it may do
 306      * so after some, but not all, bytes have been read. Consequently the input
 307      * stream may not be at end of stream and may be in an inconsistent state.
 308      * It is strongly recommended that the stream be promptly closed if an I/O
 309      * error occurs.
 310      *




 311      * @return a byte array containing the bytes read from this input stream
 312      * @throws IOException if an I/O error occurs
 313      * @throws OutOfMemoryError if an array of the required size cannot be
 314      *         allocated. For example, if an array larger than {@code 2GB} would
 315      *         be required to store the bytes.
 316      *
 317      * @since 9
 318      */
 319     public byte[] readAllBytes() throws IOException {





















































 320         List<byte[]> bufs = null;
 321         byte[] result = null;
 322         int total = 0;

 323         int n;
 324         do {
 325             byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
 326             int nread = 0;
 327 
 328             // read to EOF which may read more or less than buffer size
 329             while ((n = read(buf, nread, buf.length - nread)) > 0) {

 330                 nread += n;

 331             }
 332 
 333             if (nread > 0) {
 334                 if (MAX_BUFFER_SIZE - total < nread) {
 335                     throw new OutOfMemoryError("Required array size too large");
 336                 }
 337                 total += nread;
 338                 if (result == null) {
 339                     result = buf;
 340                 } else {
 341                     if (bufs == null) {
 342                         bufs = new ArrayList<>();
 343                         bufs.add(result);
 344                     }
 345                     bufs.add(buf);
 346                 }
 347             }
 348         } while (n >= 0); // if the last call to read returned -1, then break


 349 
 350         if (bufs == null) {
 351             if (result == null) {
 352                 return new byte[0];
 353             }
 354             return result.length == total ?
 355                 result : Arrays.copyOf(result, total);
 356         }
 357 
 358         result = new byte[total];
 359         int offset = 0;
 360         int remaining = total;
 361         for (byte[] b : bufs) {
 362             int len = Math.min(b.length, remaining);
 363             System.arraycopy(b, 0, result, offset, len);
 364             offset += len;
 365             remaining -= len;
 366         }
 367 
 368         return result;
 369     }
 370 
 371     /**
 372      * Reads the requested number of bytes from the input stream into the given
 373      * byte array. This method blocks until {@code len} bytes of input data have
 374      * been read, end of stream is detected, or an exception is thrown. The
 375      * number of bytes actually read, possibly zero, is returned. This method
 376      * does not close the input stream.
 377      *
 378      * <p> In the case where end of stream is reached before {@code len} bytes
 379      * have been read, then the actual number of bytes read will be returned.
 380      * When this stream reaches end of stream, further invocations of this
 381      * method will return zero.
 382      *
 383      * <p> If {@code len} is zero, then no bytes are read and {@code 0} is
 384      * returned; otherwise, there is an attempt to read up to {@code len} bytes.
 385      *




  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      * Returns a new {@code InputStream} that reads no bytes. The returned
  60      * stream is initially open.  The stream is closed by calling the
  61      * {@code close()} method.  Subsequent calls to {@code close()} have no
  62      * effect.
  63      *
  64      * <p> While the stream is open, the {@code available()}, {@code read()},
  65      * {@code read(byte[])}, {@code read(byte[], int, int)},
  66      * {@code readAllBytes()}, {@code readNBytes(byte[], int, int)},
  67      * {@code readNBytes(int)}, {@code skip(long)}, and
  68      * {@code transferTo()} methods all behave as if end of stream has been
  69      * reached.  After the stream has been closed, these methods all throw
  70      * {@code IOException}.
  71      *
  72      * <p> The {@code markSupported()} method returns {@code false}.  The
  73      * {@code mark()} method does nothing, and the {@code reset()} method
  74      * throws {@code IOException}.
  75      *
  76      * @return an {@code InputStream} which contains no bytes
  77      *
  78      * @since 11
  79      */
  80     public static InputStream nullInputStream() {
  81         return new InputStream() {
  82             private volatile boolean closed;
  83 
  84             private void ensureOpen() throws IOException {
  85                 if (closed) {
  86                     throw new IOException("Stream closed");
  87                 }


 107                 }
 108                 ensureOpen();
 109                 return -1;
 110             }
 111 
 112             @Override
 113             public byte[] readAllBytes() throws IOException {
 114                 ensureOpen();
 115                 return new byte[0];
 116             }
 117 
 118             @Override
 119             public int readNBytes(byte[] b, int off, int len)
 120                 throws IOException {
 121                 Objects.checkFromIndexSize(off, len, b.length);
 122                 ensureOpen();
 123                 return 0;
 124             }
 125 
 126             @Override
 127             public byte[] readNBytes(int len) throws IOException {
 128                 if (len < 0) {
 129                     throw new IllegalArgumentException("len < 0");
 130                 }
 131                 ensureOpen();
 132                 return new byte[0];
 133             }
 134 
 135             @Override
 136             public long skip(long n) throws IOException {
 137                 ensureOpen();
 138                 return 0L;
 139             }
 140 
 141             @Override
 142             public long transferTo(OutputStream out) throws IOException {
 143                 Objects.requireNonNull(out);
 144                 ensureOpen();
 145                 return 0L;
 146             }
 147 
 148             @Override
 149             public void close() throws IOException {
 150                 closed = true;
 151             }
 152         };
 153     }
 154 
 155     /**


 226      * bytes actually read; these bytes will be stored in elements
 227      * <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>,
 228      * leaving elements <code>b[off+</code><i>k</i><code>]</code> through
 229      * <code>b[off+len-1]</code> unaffected.
 230      *
 231      * <p> In every case, elements <code>b[0]</code> through
 232      * <code>b[off]</code> and elements <code>b[off+len]</code> through
 233      * <code>b[b.length-1]</code> are unaffected.
 234      *
 235      * <p> The <code>read(b,</code> <code>off,</code> <code>len)</code> method
 236      * for class <code>InputStream</code> simply calls the method
 237      * <code>read()</code> repeatedly. If the first such call results in an
 238      * <code>IOException</code>, that exception is returned from the call to
 239      * the <code>read(b,</code> <code>off,</code> <code>len)</code> method.  If
 240      * any subsequent call to <code>read()</code> results in a
 241      * <code>IOException</code>, the exception is caught and treated as if it
 242      * were end of file; the bytes read up to that point are stored into
 243      * <code>b</code> and the number of bytes read before the exception
 244      * occurred is returned. The default implementation of this method blocks
 245      * until the requested amount of input data <code>len</code> has been read,
 246      * end of file is detected, or an exception is thrown. Subclasses are
 247      * encouraged to provide a more efficient implementation of this method.
 248      *
 249      * @param      b     the buffer into which the data is read.
 250      * @param      off   the start offset in array <code>b</code>
 251      *                   at which the data is written.
 252      * @param      len   the maximum number of bytes to read.
 253      * @return     the total number of bytes read into the buffer, or
 254      *             <code>-1</code> if there is no more data because the end of
 255      *             the stream has been reached.
 256      * @exception  IOException If the first byte cannot be read for any reason
 257      * other than end of file, or if the input stream has been closed, or if
 258      * some other I/O error occurs.
 259      * @exception  NullPointerException If <code>b</code> is <code>null</code>.
 260      * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
 261      * <code>len</code> is negative, or <code>len</code> is greater than
 262      * <code>b.length - off</code>
 263      * @see        java.io.InputStream#read()
 264      */
 265     public int read(byte b[], int off, int len) throws IOException {
 266         Objects.checkFromIndexSize(off, len, b.length);
 267         if (len == 0) {


 301      * all remaining bytes have been read and end of stream is detected, or an
 302      * exception is thrown. This method does not close the input stream.
 303      *
 304      * <p> When this stream reaches end of stream, further invocations of this
 305      * method will return an empty byte array.
 306      *
 307      * <p> Note that this method is intended for simple cases where it is
 308      * convenient to read all bytes into a byte array. It is not intended for
 309      * reading input streams with large amounts of data.
 310      *
 311      * <p> The behavior for the case where the input stream is <i>asynchronously
 312      * closed</i>, or the thread interrupted during the read, is highly input
 313      * stream specific, and therefore not specified.
 314      *
 315      * <p> If an I/O error occurs reading from the input stream, then it may do
 316      * so after some, but not all, bytes have been read. Consequently the input
 317      * stream may not be at end of stream and may be in an inconsistent state.
 318      * It is strongly recommended that the stream be promptly closed if an I/O
 319      * error occurs.
 320      *
 321      * @implSpec
 322      * This method invokes {@link #readNBytes(int)} with a length of
 323      * {@link Integer#MAX_VALUE}.
 324      *
 325      * @return a byte array containing the bytes read from this input stream
 326      * @throws IOException if an I/O error occurs
 327      * @throws OutOfMemoryError if an array of the required size cannot be
 328      *         allocated.

 329      *
 330      * @since 9
 331      */
 332     public byte[] readAllBytes() throws IOException {
 333         return readNBytes(Integer.MAX_VALUE);
 334     }
 335 
 336     /**
 337      * Reads up to a specified number of bytes from the input stream. This
 338      * method blocks until the requested number of bytes have been read, end
 339      * of stream is detected, or an exception is thrown. This method does not
 340      * close the input stream.
 341      *
 342      * <p> The length of the returned array equals the number of bytes read
 343      * from the stream. If {@code len} is zero, then no bytes are read and
 344      * an empty byte array is returned. Otherwise, up to {@code len} bytes
 345      * are read from the stream. Fewer than {@code len} bytes may be read if
 346      * end of stream is encountered.
 347      *
 348      * <p> When this stream reaches end of stream, further invocations of this
 349      * method will return an empty byte array.
 350      *
 351      * <p> Note that this method is intended for simple cases where it is
 352      * convenient to read the specified number of bytes into a byte array. The
 353      * total amount of memory allocated by this method is proportional to the
 354      * number of bytes read from the stream which is bounded by {@code len}.
 355      * Therefore, the method may be safely called with very large values of
 356      * {@code len} provided sufficient memory is available.
 357      *
 358      * <p> The behavior for the case where the input stream is <i>asynchronously
 359      * closed</i>, or the thread interrupted during the read, is highly input
 360      * stream specific, and therefore not specified.
 361      *
 362      * <p> If an I/O error occurs reading from the input stream, then it may do
 363      * so after some, but not all, bytes have been read. Consequently the input
 364      * stream may not be at end of stream and may be in an inconsistent state.
 365      * It is strongly recommended that the stream be promptly closed if an I/O
 366      * error occurs.
 367      *
 368      * @implNote
 369      * The number of bytes allocated to read data from this stream and return
 370      * the result is bounded by {@code 2*(long)len}, inclusive.
 371      *
 372      * @param len the maximum number of bytes to read
 373      * @return a byte array containing the bytes read from this input stream
 374      * @throws IllegalArgumentException if {@code length} is negative
 375      * @throws IOException if an I/O error occurs
 376      * @throws OutOfMemoryError if an array of the required size cannot be
 377      *         allocated.
 378      *
 379      * @since 11
 380      */
 381     public byte[] readNBytes(int len) throws IOException {
 382         if (len < 0) {
 383             throw new IllegalArgumentException("len < 0");
 384         }
 385 
 386         List<byte[]> bufs = null;
 387         byte[] result = null;
 388         int total = 0;
 389         int remaining = len;
 390         int n;
 391         do {
 392             byte[] buf = new byte[Math.min(remaining, DEFAULT_BUFFER_SIZE)];
 393             int nread = 0;
 394 
 395             // read to EOF which may read more or less than buffer size
 396             while ((n = read(buf, nread,
 397                     Math.min(buf.length - nread, remaining))) > 0) {
 398                 nread += n;
 399                 remaining -= n;
 400             }
 401 
 402             if (nread > 0) {
 403                 if (MAX_BUFFER_SIZE - total < nread) {
 404                     throw new OutOfMemoryError("Required array size too large");
 405                 }
 406                 total += nread;
 407                 if (result == null) {
 408                     result = buf;
 409                 } else {
 410                     if (bufs == null) {
 411                         bufs = new ArrayList<>();
 412                         bufs.add(result);
 413                     }
 414                     bufs.add(buf);
 415                 }
 416             }
 417             // if the last call to read returned -1 or the number of bytes
 418             // requested have been read then break
 419         } while (n >= 0 && remaining > 0);
 420 
 421         if (bufs == null) {
 422             if (result == null) {
 423                 return new byte[0];
 424             }
 425             return result.length == total ?
 426                 result : Arrays.copyOf(result, total);
 427         }
 428 
 429         result = new byte[total];
 430         int offset = 0;
 431         remaining = total;
 432         for (byte[] b : bufs) {
 433             int count = Math.min(b.length, remaining);
 434             System.arraycopy(b, 0, result, offset, count);
 435             offset += count;
 436             remaining -= count;
 437         }
 438 
 439         return result;
 440     }
 441 
 442     /**
 443      * Reads the requested number of bytes from the input stream into the given
 444      * byte array. This method blocks until {@code len} bytes of input data have
 445      * been read, end of stream is detected, or an exception is thrown. The
 446      * number of bytes actually read, possibly zero, is returned. This method
 447      * does not close the input stream.
 448      *
 449      * <p> In the case where end of stream is reached before {@code len} bytes
 450      * have been read, then the actual number of bytes read will be returned.
 451      * When this stream reaches end of stream, further invocations of this
 452      * method will return zero.
 453      *
 454      * <p> If {@code len} is zero, then no bytes are read and {@code 0} is
 455      * returned; otherwise, there is an attempt to read up to {@code len} bytes.
 456      *


< prev index next >