java io InputSteam

1. Inputstream的类层次

image

看看jdk源代码中是如何描述该类的:

   
   
   
   
public abstract class InputStream implements Closeable

抽象类不能被实例化, 子类实现或继承该类方法, 所以我们经常看到

   
   
   
   
InputStream in = new FileInputStream( " /opt/1.txt " );

2. InputStream类定义了字节流的基本操作

image

我们可以查看第三个read方法的源代码, 可以看出来InputStream是一个字节一个字节的读取的

注意观察for循环里面的字节读取。 因为nio是以块的方式读取, 所以对某些应用场景性能上要优于io

   
   
   
   
public int read( byte b[], int off, int len) throws IOException { // ..... int c = read(); if (c == - 1 ) { return - 1 ; } b[off] = ( byte )c; int i = 1 ; try { for (; i < len ; i ++ ) { c = read(); if (c == - 1 ) { break ; } b[off + i] = ( byte )c; } } catch (IOException ee) { } return i; }

关于read方法,还有一个比较重要的地方,

   
   
   
   
/** * Reads the next byte of data from the input stream. The value byte is * returned as an int in the range 0 to 255. * If no byte is available because the end of the stream * has been reached, the value -1 is returned. This method * blocks until input data is available, the end of the stream is detected, * or an exception is thrown. * * <p> A subclass must provide an implementation of this method. * * @return the next byte of data, or -1 if the end of the * stream is reached. * @exception IOException if an I/O error occurs. */ public abstract int read() throws IOException;

大家注意这句话:  blocks until input data is available, the end of the stream is detected

就是说是一直阻塞直到检测到流末尾

你可能感兴趣的:(java io InputSteam)