引入包和继承关系:
无引入包
继承InputStream类
类作用注释如下:
/** * A <code>ByteArrayInputStream</code> contains * an internal buffer that contains bytes that * may be read from the stream. An internal * counter keeps track of the next byte to * be supplied by the <code>read</code> method. * <p> * Closing a <tt>ByteArrayInputStream</tt> has no effect. The methods in * this class can be called after the stream has been closed without * generating an <tt>IOException</tt>. * * @author Arthur van Hoff * @see java.io.StringBufferInputStream * @since JDK1.0 */
大意如下:
ByteArrayInputStream类包含一个缓冲区用来储存可能被输入流读取的byte数据
内置的记数标记保证缓冲内下一个byte可以被read方法读取
关闭ByteArrayInputStream是毫无作用的,这个方法在这个类中的流已经被关闭后可以被调用(不产生IO异常)
含有四个变量:
byte缓冲区:
protected byte buf[];
读取指针:
protected int pos;
标记点:
protected int mark = 0;
当前有效长度:(缓冲区使用长度)
protected int count;
含有十个方法:
构造方法(从头拷贝一个byte数组):
public ByteArrayInputStream(byte buf[]) { this.buf = buf; this.pos = 0; this.count = buf.length; }
构造方法(获得部分byte长度数组,实质拷贝全部,但读取指针不指向数组头):
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; }
从输入缓冲区中读取数据(一个数组单元数据),返回被读取单元的byte码:
public synchronized int read() { return (pos < count) ? (buf[pos++] & 0xff) : -1; }
从输入缓冲区读取数据(批量读取),返回实际读取长度:
public synchronized int read(byte b[], int off, int len) {//off为起始读取位置,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; }
跳过后面n个单元读取:
public synchronized long skip(long n) { long k = count - pos; if (n < k) {//判定是否跳出有效值区间 k = n < 0 ? 0 : n; } pos += k; return k; }
返回当前剩余有效值:
public synchronized int available() { return count - pos; }
检查是否支持标记操作:
public boolean markSupported() { return true; }
标记当前位置:
public void mark(int readAheadLimit) { mark = pos; }
重置标记:
public synchronized void reset() { pos = mark; }
关闭流(毫无作用):
public void close() throws IOException { }
ByteArrayInputStream类似于BufferedInputStream,但是结构要更为简单:直接读入输入的byte数组,但初始化后就不能向缓冲区添加数据,数据没有动态刷新功能。在数据量小时较为好用。