【io包 InputStream】 --源码分析

字节输入流,是一个抽象类,核心是通过read()方法,从数据源中读取一个个字节出来,另有skip,mark功能

核心是read方法,源码:

public abstract int read() throws IOException;

抽象方法,必须由子类实现;从什么地方读?数据源来自哪里?这个是由子类提供的,如FileInputStream是从文件中读,ByteArrayInputStream是从byte数组中读

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();
        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;
    }
从输入流读取len个字节数据,并保存到数组中。读取的数组最多为len。真正读取的字节数目将作为返回值返回。
若len=0,则没有字节需要读取,返回为0;若字节不可达,则返回-1。
读取到的第一个字节保存到b[off]中,下一个保存在b[off+1],以此类推。

posted on 2019-09-04 16:23  zhulu666  阅读(168)  评论(0)    收藏  举报

导航