Java IO可以分为字节输入输出流和字符输入输出流,但它们都属于阻塞式IO(Blocking IO)的实现。程序只能以流式的方式顺序的从一个流中读取一个或多个字节,不能随意的改变读取指针的位置。为什么这样说呢?下面我们分别看一下其他一些实现类的源码,从而理解一下为什么说它们是阻塞的。

    InputStream
    **
    以FileInputStream为例进行说明,首先看一下read方法的源码实现,如下所示:

    1. /**
    2. * Reads a byte of data from this input stream. This method blocks
    3. * if no input is yet available.
    4. *
    5. * @return the next byte of data, or <code>-1</code> if the end of the
    6. * file is reached.
    7. * @exception IOException if an I/O error occurs.
    8. */
    9. public int read() throws IOException {
    10. return read0();
    11. }
    12. private native int read0() throws IOException;

    可以看到,read方法的实现最终调用的是native表示的本地方法,数据IO的工作并不是由InputStream自身完成的。再看方法描述可以发现:

    • 调用该方法时,如果没有数据可读,方法会一直阻塞
    • 读取时按照逐字节的方式读取,如果读取完毕则返回-1