Java 分析源码InputStream

Java IO InputStream源码

 

InputStream是Java字节流中输入流的父类,并且是抽象类。 
有两个static final变量MAX_SKIP_BUFFER_SIZE DEFAULT_BUFFER_SIZE MAX_BUFFER_SIZE 
一个抽象函数read()

 

属性介绍 
MAX_SKIP_BUFFER_SIZE = 2048 
DEFAULT_BUFFER_SIZE = 8192 
MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8

方法介绍 
public abstract int read() 抽象方法 
从输入流中读取下一个字节的数据。值字节在0到255范围内作为整数返回。如果没有可用的字节,因为已经到达了流的末端,则返回值-1。 
当出现io阻塞时报IOException

public int read(byte b[]) 
引用public int read(byte b[], int off, int len)

​public int read(byte b[]) throws IOException {
    return read(b, 0, b.length);
}

public int read(byte b[], int off, int len) 
从输入流读取数据到字节数组。试图读取尽可能多的len字节,但是可以读取较小的数字。实际上读取的字节数作为一个整数返回。这个方法会阻塞直到输入数据可用,检测到文件的结束,或者抛出异常。 
本方法通过read()以bety的形式读取数据。并存入b[]中。off为b起始,len为读取长度

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;
    }

public long skip(long n) 
利用read(byte b[], int off, int len)使指针偏移达到跳转的效果。

public long skip(long n) throws IOException {

        long remaining = n;
        int nr;

        if (n <= 0) {
            return 0;
        }

        int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining);
        byte[] skipBuffer = new byte[size];
        while (remaining > 0) {
            nr = read(skipBuffer, 0, (int)Math.min(size, remaining));
            if (nr < 0) {
                break;
            }
            remaining -= nr;
        }

        return n - remaining;
    }

public int available() 
这里的方法更像是一个模板方法,不用在意。

public int available() throws IOException {
    return 0;
}

public void close() 
模板方法

public synchronized void mark(int readlimit) 
又一个 
标记这个输入流中的当前位置。对重置方法的后续调用将在最后一个标记的位置重新定位该流,以便随后的读取重新读取相同的字节。

public synchronized void mark(int readlimit) {}

public synchronized void reset() 
将此流重新定位到在此输入流上最后调用标记方法时的位置

public synchronized void reset() throws IOException {
    throw new IOException("mark/reset not supported");
}

public boolean markSupported() 
是否支持标记和重置是特定输入流实例的不变属性

public boolean markSupported() {
    return false;
}

转载于:https://my.oschina.net/u/3634161/blog/1815115

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值