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 33 /** 34 * This abstract class is the superclass of all classes representing 35 * an input stream of bytes. 36 * 37 * <p> Applications that need to define a subclass of <code>InputStream</code> 38 * must always provide a method that returns the next byte of input. 39 * 40 * @author Arthur van Hoff 41 * @see java.io.BufferedInputStream 42 * @see java.io.ByteArrayInputStream 43 * @see java.io.DataInputStream 44 * @see java.io.FilterInputStream 45 * @see java.io.InputStream#read() 46 * @see java.io.OutputStream 47 * @see java.io.PushbackInputStream 48 * @since 1.0 49 */ 50 public abstract class InputStream implements Closeable { 51 52 // MAX_SKIP_BUFFER_SIZE is used to determine the maximum buffer size to 53 // use when skipping. 54 private static final int MAX_SKIP_BUFFER_SIZE = 2048; 55 56 private static final int DEFAULT_BUFFER_SIZE = 8192; 57 58 /** 59 * 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 } 87 } 88 89 @Override 90 public int available () throws IOException { 91 ensureOpen(); 92 return 0; 93 } 94 95 @Override 96 public int read() throws IOException { 97 ensureOpen(); 98 return -1; 99 } 100 101 @Override 102 public int read(byte[] b, int off, int len) throws IOException { 103 Objects.checkFromIndexSize(off, len, b.length); 104 if (len == 0) { 105 return 0; 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 /** 146 * Reads the next byte of data from the input stream. The value byte is 147 * returned as an <code>int</code> in the range <code>0</code> to 148 * <code>255</code>. If no byte is available because the end of the stream 149 * has been reached, the value <code>-1</code> is returned. This method 150 * blocks until input data is available, the end of the stream is detected, 151 * or an exception is thrown. 152 * 153 * <p> A subclass must provide an implementation of this method. 154 * 155 * @return the next byte of data, or <code>-1</code> if the end of the 156 * stream is reached. 157 * @exception IOException if an I/O error occurs. 158 */ 159 public abstract int read() throws IOException; 160 161 /** 162 * Reads some number of bytes from the input stream and stores them into 163 * the buffer array <code>b</code>. The number of bytes actually read is 164 * returned as an integer. This method blocks until input data is 165 * available, end of file is detected, or an exception is thrown. 166 * 167 * <p> If the length of <code>b</code> is zero, then no bytes are read and 168 * <code>0</code> is returned; otherwise, there is an attempt to read at 169 * least one byte. If no byte is available because the stream is at the 170 * end of the file, the value <code>-1</code> is returned; otherwise, at 171 * least one byte is read and stored into <code>b</code>. 172 * 173 * <p> The first byte read is stored into element <code>b[0]</code>, the 174 * next one into <code>b[1]</code>, and so on. The number of bytes read is, 175 * at most, equal to the length of <code>b</code>. Let <i>k</i> be the 176 * number of bytes actually read; these bytes will be stored in elements 177 * <code>b[0]</code> through <code>b[</code><i>k</i><code>-1]</code>, 178 * leaving elements <code>b[</code><i>k</i><code>]</code> through 179 * <code>b[b.length-1]</code> unaffected. 180 * 181 * <p> The <code>read(b)</code> method for class <code>InputStream</code> 182 * has the same effect as: <pre><code> read(b, 0, b.length) </code></pre> 183 * 184 * @param b the buffer into which the data is read. 185 * @return the total number of bytes read into the buffer, or 186 * <code>-1</code> if there is no more data because the end of 187 * the stream has been reached. 188 * @exception IOException If the first byte cannot be read for any reason 189 * other than the end of the file, if the input stream has been closed, or 190 * if some other I/O error occurs. 191 * @exception NullPointerException if <code>b</code> is <code>null</code>. 192 * @see java.io.InputStream#read(byte[], int, int) 193 */ 194 public int read(byte b[]) throws IOException { 195 return read(b, 0, b.length); 196 } 197 198 /** 199 * Reads up to <code>len</code> bytes of data from the input stream into 200 * an array of bytes. An attempt is made to read as many as 201 * <code>len</code> bytes, but a smaller number may be read. 202 * The number of bytes actually read is returned as an integer. 203 * 204 * <p> This method blocks until input data is available, end of file is 205 * detected, or an exception is thrown. 206 * 207 * <p> If <code>len</code> is zero, then no bytes are read and 208 * <code>0</code> is returned; otherwise, there is an attempt to read at 209 * least one byte. If no byte is available because the stream is at end of 210 * file, the value <code>-1</code> is returned; otherwise, at least one 211 * byte is read and stored into <code>b</code>. 212 * 213 * <p> The first byte read is stored into element <code>b[off]</code>, the 214 * next one into <code>b[off+1]</code>, and so on. The number of bytes read 215 * is, at most, equal to <code>len</code>. Let <i>k</i> be the number of 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) { 258 return 0; 259 } 260 261 int c = read(); 262 if (c == -1) { 263 return -1; 264 } 265 b[off] = (byte)c; 266 267 int i = 1; 268 try { 269 for (; i < len ; i++) { 270 c = read(); 271 if (c == -1) { 272 break; 273 } 274 b[off + i] = (byte)c; 275 } 276 } catch (IOException ee) { 277 } 278 return i; 279 } 280 281 /** 282 * The maximum size of array to allocate. 283 * Some VMs reserve some header words in an array. 284 * Attempts to allocate larger arrays may result in 285 * OutOfMemoryError: Requested array size exceeds VM limit 286 */ 287 private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8; 288 289 /** 290 * Reads all remaining bytes from the input stream. This method blocks until 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 * 386 * <p> The first byte read is stored into element {@code b[off]}, the next 387 * one in to {@code b[off+1]}, and so on. The number of bytes read is, at 388 * most, equal to {@code len}. Let <i>k</i> be the number of bytes actually 389 * read; these bytes will be stored in elements {@code b[off]} through 390 * {@code b[off+}<i>k</i>{@code -1]}, leaving elements {@code b[off+}<i>k</i> 391 * {@code ]} through {@code b[off+len-1]} unaffected. 392 * 393 * <p> The behavior for the case where the input stream is <i>asynchronously 394 * closed</i>, or the thread interrupted during the read, is highly input 395 * stream specific, and therefore not specified. 396 * 397 * <p> If an I/O error occurs reading from the input stream, then it may do 398 * so after some, but not all, bytes of {@code b} have been updated with 399 * data from the input stream. Consequently the input stream and {@code b} 400 * may be in an inconsistent state. It is strongly recommended that the 401 * stream be promptly closed if an I/O error occurs. 402 * 403 * @param b the byte array into which the data is read 404 * @param off the start offset in {@code b} at which the data is written 405 * @param len the maximum number of bytes to read 406 * @return the actual number of bytes read into the buffer 407 * @throws IOException if an I/O error occurs 408 * @throws NullPointerException if {@code b} is {@code null} 409 * @throws IndexOutOfBoundsException If {@code off} is negative, {@code len} 410 * is negative, or {@code len} is greater than {@code b.length - off} 411 * 412 * @since 9 413 */ 414 public int readNBytes(byte[] b, int off, int len) throws IOException { 415 Objects.checkFromIndexSize(off, len, b.length); 416 417 int n = 0; 418 while (n < len) { 419 int count = read(b, off + n, len - n); 420 if (count < 0) 421 break; 422 n += count; 423 } 424 return n; 425 } 426 427 /** 428 * Skips over and discards <code>n</code> bytes of data from this input 429 * stream. The <code>skip</code> method may, for a variety of reasons, end 430 * up skipping over some smaller number of bytes, possibly <code>0</code>. 431 * This may result from any of a number of conditions; reaching end of file 432 * before <code>n</code> bytes have been skipped is only one possibility. 433 * The actual number of bytes skipped is returned. If {@code n} is 434 * negative, the {@code skip} method for class {@code InputStream} always 435 * returns 0, and no bytes are skipped. Subclasses may handle the negative 436 * value differently. 437 * 438 * <p> The <code>skip</code> method implementation of this class creates a 439 * byte array and then repeatedly reads into it until <code>n</code> bytes 440 * have been read or the end of the stream has been reached. Subclasses are 441 * encouraged to provide a more efficient implementation of this method. 442 * For instance, the implementation may depend on the ability to seek. 443 * 444 * @param n the number of bytes to be skipped. 445 * @return the actual number of bytes skipped. 446 * @throws IOException if an I/O error occurs. 447 */ 448 public long skip(long n) throws IOException { 449 450 long remaining = n; 451 int nr; 452 453 if (n <= 0) { 454 return 0; 455 } 456 457 int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining); 458 byte[] skipBuffer = new byte[size]; 459 while (remaining > 0) { 460 nr = read(skipBuffer, 0, (int)Math.min(size, remaining)); 461 if (nr < 0) { 462 break; 463 } 464 remaining -= nr; 465 } 466 467 return n - remaining; 468 } 469 470 /** 471 * Returns an estimate of the number of bytes that can be read (or 472 * skipped over) from this input stream without blocking by the next 473 * invocation of a method for this input stream. The next invocation 474 * might be the same thread or another thread. A single read or skip of this 475 * many bytes will not block, but may read or skip fewer bytes. 476 * 477 * <p> Note that while some implementations of {@code InputStream} will return 478 * the total number of bytes in the stream, many will not. It is 479 * never correct to use the return value of this method to allocate 480 * a buffer intended to hold all data in this stream. 481 * 482 * <p> A subclass' implementation of this method may choose to throw an 483 * {@link IOException} if this input stream has been closed by 484 * invoking the {@link #close()} method. 485 * 486 * <p> The {@code available} method for class {@code InputStream} always 487 * returns {@code 0}. 488 * 489 * <p> This method should be overridden by subclasses. 490 * 491 * @return an estimate of the number of bytes that can be read (or skipped 492 * over) from this input stream without blocking or {@code 0} when 493 * it reaches the end of the input stream. 494 * @exception IOException if an I/O error occurs. 495 */ 496 public int available() throws IOException { 497 return 0; 498 } 499 500 /** 501 * Closes this input stream and releases any system resources associated 502 * with the stream. 503 * 504 * <p> The <code>close</code> method of <code>InputStream</code> does 505 * nothing. 506 * 507 * @exception IOException if an I/O error occurs. 508 */ 509 public void close() throws IOException {} 510 511 /** 512 * Marks the current position in this input stream. A subsequent call to 513 * the <code>reset</code> method repositions this stream at the last marked 514 * position so that subsequent reads re-read the same bytes. 515 * 516 * <p> The <code>readlimit</code> arguments tells this input stream to 517 * allow that many bytes to be read before the mark position gets 518 * invalidated. 519 * 520 * <p> The general contract of <code>mark</code> is that, if the method 521 * <code>markSupported</code> returns <code>true</code>, the stream somehow 522 * remembers all the bytes read after the call to <code>mark</code> and 523 * stands ready to supply those same bytes again if and whenever the method 524 * <code>reset</code> is called. However, the stream is not required to 525 * remember any data at all if more than <code>readlimit</code> bytes are 526 * read from the stream before <code>reset</code> is called. 527 * 528 * <p> Marking a closed stream should not have any effect on the stream. 529 * 530 * <p> The <code>mark</code> method of <code>InputStream</code> does 531 * nothing. 532 * 533 * @param readlimit the maximum limit of bytes that can be read before 534 * the mark position becomes invalid. 535 * @see java.io.InputStream#reset() 536 */ 537 public synchronized void mark(int readlimit) {} 538 539 /** 540 * Repositions this stream to the position at the time the 541 * <code>mark</code> method was last called on this input stream. 542 * 543 * <p> The general contract of <code>reset</code> is: 544 * 545 * <ul> 546 * <li> If the method <code>markSupported</code> returns 547 * <code>true</code>, then: 548 * 549 * <ul><li> If the method <code>mark</code> has not been called since 550 * the stream was created, or the number of bytes read from the stream 551 * since <code>mark</code> was last called is larger than the argument 552 * to <code>mark</code> at that last call, then an 553 * <code>IOException</code> might be thrown. 554 * 555 * <li> If such an <code>IOException</code> is not thrown, then the 556 * stream is reset to a state such that all the bytes read since the 557 * most recent call to <code>mark</code> (or since the start of the 558 * file, if <code>mark</code> has not been called) will be resupplied 559 * to subsequent callers of the <code>read</code> method, followed by 560 * any bytes that otherwise would have been the next input data as of 561 * the time of the call to <code>reset</code>. </ul> 562 * 563 * <li> If the method <code>markSupported</code> returns 564 * <code>false</code>, then: 565 * 566 * <ul><li> The call to <code>reset</code> may throw an 567 * <code>IOException</code>. 568 * 569 * <li> If an <code>IOException</code> is not thrown, then the stream 570 * is reset to a fixed state that depends on the particular type of the 571 * input stream and how it was created. The bytes that will be supplied 572 * to subsequent callers of the <code>read</code> method depend on the 573 * particular type of the input stream. </ul></ul> 574 * 575 * <p>The method <code>reset</code> for class <code>InputStream</code> 576 * does nothing except throw an <code>IOException</code>. 577 * 578 * @exception IOException if this stream has not been marked or if the 579 * mark has been invalidated. 580 * @see java.io.InputStream#mark(int) 581 * @see java.io.IOException 582 */ 583 public synchronized void reset() throws IOException { 584 throw new IOException("mark/reset not supported"); 585 } 586 587 /** 588 * Tests if this input stream supports the <code>mark</code> and 589 * <code>reset</code> methods. Whether or not <code>mark</code> and 590 * <code>reset</code> are supported is an invariant property of a 591 * particular input stream instance. The <code>markSupported</code> method 592 * of <code>InputStream</code> returns <code>false</code>. 593 * 594 * @return <code>true</code> if this stream instance supports the mark 595 * and reset methods; <code>false</code> otherwise. 596 * @see java.io.InputStream#mark(int) 597 * @see java.io.InputStream#reset() 598 */ 599 public boolean markSupported() { 600 return false; 601 } 602 603 /** 604 * Reads all bytes from this input stream and writes the bytes to the 605 * given output stream in the order that they are read. On return, this 606 * input stream will be at end of stream. This method does not close either 607 * stream. 608 * <p> 609 * This method may block indefinitely reading from the input stream, or 610 * writing to the output stream. The behavior for the case where the input 611 * and/or output stream is <i>asynchronously closed</i>, or the thread 612 * interrupted during the transfer, is highly input and output stream 613 * specific, and therefore not specified. 614 * <p> 615 * If an I/O error occurs reading from the input stream or writing to the 616 * output stream, then it may do so after some bytes have been read or 617 * written. Consequently the input stream may not be at end of stream and 618 * one, or both, streams may be in an inconsistent state. It is strongly 619 * recommended that both streams be promptly closed if an I/O error occurs. 620 * 621 * @param out the output stream, non-null 622 * @return the number of bytes transferred 623 * @throws IOException if an I/O error occurs when reading or writing 624 * @throws NullPointerException if {@code out} is {@code null} 625 * 626 * @since 9 627 */ 628 public long transferTo(OutputStream out) throws IOException { 629 Objects.requireNonNull(out, "out"); 630 long transferred = 0; 631 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 632 int read; 633 while ((read = this.read(buffer, 0, DEFAULT_BUFFER_SIZE)) >= 0) { 634 out.write(buffer, 0, read); 635 transferred += read; 636 } 637 return transferred; 638 } 639 }