Home | History | Annotate | Download | only in io
      1 /*
      2  *  Licensed to the Apache Software Foundation (ASF) under one or more
      3  *  contributor license agreements.  See the NOTICE file distributed with
      4  *  this work for additional information regarding copyright ownership.
      5  *  The ASF licenses this file to You under the Apache License, Version 2.0
      6  *  (the "License"); you may not use this file except in compliance with
      7  *  the License.  You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  *  Unless required by applicable law or agreed to in writing, software
     12  *  distributed under the License is distributed on an "AS IS" BASIS,
     13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  *  See the License for the specific language governing permissions and
     15  *  limitations under the License.
     16  */
     17 
     18 package java.io;
     19 
     20 import java.util.Arrays;
     21 import libcore.io.Streams;
     22 
     23 /**
     24  * A readable source of bytes.
     25  *
     26  * <p>Most clients will use input streams that read data from the file system
     27  * ({@link FileInputStream}), the network ({@link java.net.Socket#getInputStream()}/{@link
     28  * java.net.HttpURLConnection#getInputStream()}), or from an in-memory byte
     29  * array ({@link ByteArrayInputStream}).
     30  *
     31  * <p>Use {@link InputStreamReader} to adapt a byte stream like this one into a
     32  * character stream.
     33  *
     34  * <p>Most clients should wrap their input stream with {@link
     35  * BufferedInputStream}. Callers that do only bulk reads may omit buffering.
     36  *
     37  * <p>Some implementations support marking a position in the input stream and
     38  * resetting back to this position later. Implementations that don't return
     39  * false from {@link #markSupported()} and throw an {@link IOException} when
     40  * {@link #reset()} is called.
     41  *
     42  * <h3>Subclassing InputStream</h3>
     43  * Subclasses that decorate another input stream should consider subclassing
     44  * {@link FilterInputStream}, which delegates all calls to the source input
     45  * stream.
     46  *
     47  * <p>All input stream subclasses should override <strong>both</strong> {@link
     48  * #read() read()} and {@link #read(byte[],int,int) read(byte[],int,int)}. The
     49  * three argument overload is necessary for bulk access to the data. This is
     50  * much more efficient than byte-by-byte access.
     51  *
     52  * @see OutputStream
     53  */
     54 public abstract class InputStream extends Object implements Closeable {
     55 
     56     /**
     57      * This constructor does nothing. It is provided for signature
     58      * compatibility.
     59      */
     60     public InputStream() {
     61         /* empty */
     62     }
     63 
     64     /**
     65      * Returns an estimated number of bytes that can be read or skipped without blocking for more
     66      * input.
     67      *
     68      * <p>Note that this method provides such a weak guarantee that it is not very useful in
     69      * practice.
     70      *
     71      * <p>Firstly, the guarantee is "without blocking for more input" rather than "without
     72      * blocking": a read may still block waiting for I/O to complete&nbsp;&mdash; the guarantee is
     73      * merely that it won't have to wait indefinitely for data to be written. The result of this
     74      * method should not be used as a license to do I/O on a thread that shouldn't be blocked.
     75      *
     76      * <p>Secondly, the result is a
     77      * conservative estimate and may be significantly smaller than the actual number of bytes
     78      * available. In particular, an implementation that always returns 0 would be correct.
     79      * In general, callers should only use this method if they'd be satisfied with
     80      * treating the result as a boolean yes or no answer to the question "is there definitely
     81      * data ready?".
     82      *
     83      * <p>Thirdly, the fact that a given number of bytes is "available" does not guarantee that a
     84      * read or skip will actually read or skip that many bytes: they may read or skip fewer.
     85      *
     86      * <p>It is particularly important to realize that you <i>must not</i> use this method to
     87      * size a container and assume that you can read the entirety of the stream without needing
     88      * to resize the container. Such callers should probably write everything they read to a
     89      * {@link ByteArrayOutputStream} and convert that to a byte array. Alternatively, if you're
     90      * reading from a file, {@link File#length} returns the current length of the file (though
     91      * assuming the file's length can't change may be incorrect, reading a file is inherently
     92      * racy).
     93      *
     94      * <p>The default implementation of this method in {@code InputStream} always returns 0.
     95      * Subclasses should override this method if they are able to indicate the number of bytes
     96      * available.
     97      *
     98      * @return the estimated number of bytes available
     99      * @throws IOException if this stream is closed or an error occurs
    100      */
    101     public int available() throws IOException {
    102         return 0;
    103     }
    104 
    105     /**
    106      * Closes this stream. Concrete implementations of this class should free
    107      * any resources during close. This implementation does nothing.
    108      *
    109      * @throws IOException
    110      *             if an error occurs while closing this stream.
    111      */
    112     public void close() throws IOException {
    113         /* empty */
    114     }
    115 
    116     /**
    117      * Sets a mark position in this InputStream. The parameter {@code readlimit}
    118      * indicates how many bytes can be read before the mark is invalidated.
    119      * Sending {@code reset()} will reposition the stream back to the marked
    120      * position provided {@code readLimit} has not been surpassed.
    121      * <p>
    122      * This default implementation does nothing and concrete subclasses must
    123      * provide their own implementation.
    124      *
    125      * @param readlimit
    126      *            the number of bytes that can be read from this stream before
    127      *            the mark is invalidated.
    128      * @see #markSupported()
    129      * @see #reset()
    130      */
    131     public void mark(int readlimit) {
    132         /* empty */
    133     }
    134 
    135     /**
    136      * Indicates whether this stream supports the {@code mark()} and
    137      * {@code reset()} methods. The default implementation returns {@code false}.
    138      *
    139      * @return always {@code false}.
    140      * @see #mark(int)
    141      * @see #reset()
    142      */
    143     public boolean markSupported() {
    144         return false;
    145     }
    146 
    147     /**
    148      * Reads a single byte from this stream and returns it as an integer in the
    149      * range from 0 to 255. Returns -1 if the end of the stream has been
    150      * reached. Blocks until one byte has been read, the end of the source
    151      * stream is detected or an exception is thrown.
    152      *
    153      * @return the byte read or -1 if the end of stream has been reached.
    154      * @throws IOException
    155      *             if the stream is closed or another IOException occurs.
    156      */
    157     public abstract int read() throws IOException;
    158 
    159     /**
    160      * Equivalent to {@code read(buffer, 0, buffer.length)}.
    161      */
    162     public int read(byte[] buffer) throws IOException {
    163         return read(buffer, 0, buffer.length);
    164     }
    165 
    166     /**
    167      * Reads at most {@code length} bytes from this stream and stores them in
    168      * the byte array {@code b} starting at {@code offset}.
    169      *
    170      * @param buffer
    171      *            the byte array in which to store the bytes read.
    172      * @param offset
    173      *            the initial position in {@code buffer} to store the bytes read
    174      *            from this stream.
    175      * @param length
    176      *            the maximum number of bytes to store in {@code b}.
    177      * @return the number of bytes actually read or -1 if the end of the stream
    178      *         has been reached.
    179      * @throws IndexOutOfBoundsException
    180      *             if {@code offset < 0} or {@code length < 0}, or if
    181      *             {@code offset + length} is greater than the length of
    182      *             {@code b}.
    183      * @throws IOException
    184      *             if the stream is closed or another IOException occurs.
    185      */
    186     public int read(byte[] buffer, int offset, int length) throws IOException {
    187         Arrays.checkOffsetAndCount(buffer.length, offset, length);
    188         for (int i = 0; i < length; i++) {
    189             int c;
    190             try {
    191                 if ((c = read()) == -1) {
    192                     return i == 0 ? -1 : i;
    193                 }
    194             } catch (IOException e) {
    195                 if (i != 0) {
    196                     return i;
    197                 }
    198                 throw e;
    199             }
    200             buffer[offset + i] = (byte) c;
    201         }
    202         return length;
    203     }
    204 
    205     /**
    206      * Resets this stream to the last marked location. Throws an
    207      * {@code IOException} if the number of bytes read since the mark has been
    208      * set is greater than the limit provided to {@code mark}, or if no mark
    209      * has been set.
    210      * <p>
    211      * This implementation always throws an {@code IOException} and concrete
    212      * subclasses should provide the proper implementation.
    213      *
    214      * @throws IOException
    215      *             if this stream is closed or another IOException occurs.
    216      */
    217     public synchronized void reset() throws IOException {
    218         throw new IOException();
    219     }
    220 
    221     /**
    222      * Skips at most {@code n} bytes in this stream. This method does nothing and returns
    223      * 0 if {@code n} is negative, but some subclasses may throw.
    224      *
    225      * <p>Note the "at most" in the description of this method: this method may choose to skip
    226      * fewer bytes than requested. Callers should <i>always</i> check the return value.
    227      *
    228      * <p>This default implementation reads bytes into a temporary
    229      * buffer. Concrete subclasses should provide their own implementation.
    230      *
    231      * @param byteCount the number of bytes to skip.
    232      * @return the number of bytes actually skipped.
    233      * @throws IOException
    234      *             if this stream is closed or another IOException occurs.
    235      */
    236     public long skip(long byteCount) throws IOException {
    237         return Streams.skipByReading(this, byteCount);
    238     }
    239 }
    240