java源码分析03-InputSteam

来源:互联网 发布:威少上赛季每场数据 编辑:程序博客网 时间:2024/06/05 21:11

最近心情有些烦躁,还是多学点java吧,最起码她不会烦你,也不会不理你。

1.类结构


InputStream是一个抽象类,实现了Closeable接口

关于Closeable接口,
public interface Closeable extends AutoCloseable {    public void close() throws IOException;}
关于AutoCloseable接口
package java.lang;/** * A resource that must be closed when it is no longer needed. * * @author Josh Bloch * @since 1.7 */public interface AutoCloseable {       void close() throws Exception;}


2.内部属性和方法介绍

构造函数就不说了
三种read方法
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();        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()每次只能读取一个字节;
read(byte[]) 调用read(byte[],int off,int len)
read(byte[],int off,int len)表示从off字节开始,读取len个字节,此处需要注意的是读取之前需要判断是否已经结束,也就是read的返回值是否为-1,还有需要注意字节数组是否越界。
唯一的属性:最大可跳过的缓存长度MAX_SKIP_BUFFER_SIZE
<pre name="code" class="java">private static final int MAX_SKIP_BUFFER_SIZE = 2048;



skip方法
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;    }
上述代码可以看出最大可跳跃长度为2048,所以第一步判断传入的跳跃长度与2048的大小关系,当然不能为
负数。
此处容易混淆,skip(9)是从第9个还是第10个字节开始读取?


mark方法,markSupported方法
public synchronized void mark(int readlimit) {}


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


reset方法
 public synchronized void reset() throws IOException {        throw new IOException("mark/reset not supported");    }
重新从起始位置开始读取

close方法
public void close() throws IOException {}

0 0
原创粉丝点击