java io流类图
IO架构介绍:
IO分为字节流和字符流处理2种类型,有对应的输入与输出流来处理文件的读写操作
输入与输出流处理的结构类似,基本上输入流(input)与输出流(output)包含对 byte ,String , file 文件的读写操作
设计模式介绍:
java IO流使用了装饰器模式和适配器模式
装饰器模式:
对现有的对象添加新的功能,同时又不改变其结构。它是作为现有的类的一个包装类。
java中FilterInputStream, FilterReader等都使用里装饰器模式,FilterInputStream实现抽象,子类根据不同的需求实现不同功能的实现;
如BufferedInputStream是对IO读的操作添加了缓存大小
如下列源码:
BufferedInputStream需要传递父类对象,根据设定的缓存区大小进行读的操作
public BufferedInputStream(InputStream in, int size) { super(in); if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buf = new byte[size]; }
适配器模式:
作为两个不兼容的接口之间的桥梁。
java调用中在不改变 A调用和B返回的情况下 新增一个C的接口进行适配A调用B的方式;
即是A调用C,C来重新组装对B的请求来实现调用B接口,最后在组装A的返回数据以适应A的接口;
IO里面的应用:
StringBufferInputStream ,ByteArrayInputStream等都是对inputStream的适配,把字节流的读取适配成byte数组或者String的读取
如下ByteArrayInputStream源码结构,ByteArrayInputStream里面定义了一个数组类型,用来接收所有预读的byte数组类型对象,在使用read同步方法进行模拟inputStream读取
public class ByteArrayInputStream extends InputStream {
protected byte buf[];protected int pos;
protected int mark = 0;
protected int count;
public ByteArrayInputStream(byte buf[]) {
this.buf = buf;
this.pos = 0;
this.count = buf.length;
}
public ByteArrayInputStream(byte buf[], int offset, int length) {
this.buf = buf;
this.pos = offset;
this.count = Math.min(offset + length, buf.length);
this.mark = offset;
}
public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}
public synchronized int read(byte b[], int off, int len) {
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
if (pos >= count) {
return -1;
}
int avail = count - pos;
if (len > avail) {
len = avail;
}
if (len <= 0) {
return 0;
}
System.arraycopy(buf, pos, b, off, len);
pos += len;
return len;
}