JDK source code parsing InputStream class uses template method mode

JDK source code analysis

The InputStream class uses the template method pattern.

Several read() methods are defined in the InputStream class  , as follows:

public abstract class InputStream implements Closeable {
    //抽象方法,要求子类必须重写
    public abstract int read() throws IOException;
​
    public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }
​
    public int read(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }
​
        int c = read(); //调用了无参的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;
    }
}

As you can see from the above code, the read() method without parameters  is an abstract method, and the subclass must be implemented.

And the  read(byte b[]) method calls the  read(byte b[], int off, int len) method,

So the method that I will focus on here is the method with three parameters.

In the 18th and 27th lines of this method, you can see that the abstract read() method without parameters is called  .

The summary is as follows: The method of reading a byte array data has been defined in the InputStream parent class is to read one byte at a time, and store it in the first index position of the array, and read len bytes of data .

How to read a byte of data specifically? Implemented by subclasses.

Guess you like

Origin blog.csdn.net/qq_39368007/article/details/114026762