BufferInputStream_BufferOutputStream
标签: java8源码
欢迎 star
思路
主要是从输入或输出流中一次读取 8192(默认) 个字节加载到内存中,用作缓存.
目的
提高数据输入或输出的速度.
BufferInputStream详解
BufferInputStream 类签名
public
class BufferedInputStream extends FilterInputStream {}
BufferInputStream 成员变量
protected volatile byte buf[];//缓存数组
protected int count;//缓存数组中的有效字节
protected int marklimit;//标记最大值
protected int markpos = -1;//缓冲区标记位置
protected int pos;//缓冲区当前索引
private static int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;//最大缓存大小
private static int DEFAULT_BUFFER_SIZE = 8192;//默认缓存大小
BufferInputStream 构造方法
/**共两个构造方法*/
//为指定输入流提供缓存,且缓存大小为默认缓冲大小的构造器.
public BufferedInputStream(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
//为指定输入流提供缓存,但缓存大小为指定大小的构造器.
public BufferedInputStream(InputStream in, int size) {
super(in);//由类签名可以看出,继承自FilterInputStream,in为其父类成员变量.
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];//初始化缓存数组的大小
}
BufferInputStream 的常用方法
read(byte[] b);
//实际上这是其父类的read(byte b[])方法,调用了read(b, 0, b.length)方法,其重写了该方法,故,调用其自己的该方法.
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
read(byte b[], int off, int len);
public synchronized int read(byte b[], int off, int len)
throws IOException
{
getBufIfOpen(); // 获取缓存数组,这里的作用是检查缓存数组是否为null.若是,则抛异常. 见(I)
if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
//数组越界