Java IO可以分为字节输入输出流和字符输入输出流,但它们都属于阻塞式IO(Blocking IO)的实现。程序只能以流式的方式顺序的从一个流中读取一个或多个字节,不能随意的改变读取指针的位置。为什么这样说呢?下面我们分别看一下其他一些实现类的源码,从而理解一下为什么说它们是阻塞的。
InputStream
**
以FileInputStream为例进行说明,首先看一下read方法的源码实现,如下所示:
/**
* Reads a byte of data from this input stream. This method blocks
* if no input is yet available.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* file is reached.
* @exception IOException if an I/O error occurs.
*/
public int read() throws IOException {
return read0();
}
private native int read0() throws IOException;
可以看到,read方法的实现最终调用的是native表示的本地方法,数据IO的工作并不是由InputStream自身完成的。再看方法描述可以发现:
- 调用该方法时,如果没有数据可读,方法会一直阻塞
- 读取时按照逐字节的方式读取,如果读取完毕则返回-1