package java.io; public class ByteArrayInputStream extends InputStream { // 保存字节输入流数据的字节数组 protected byte buf[]; // 下一个会被读取的字节的索引 protected int pos; // 标记的索引 protected int mark = 0; // 字节流的长度 protected int count; // 构造函数:建立一个内容为buf的字节流 public ByteArrayInputStream(byte buf[]) { // 初始化“字节流对应的字节数组为buf” this.buf = buf; // 初始化“下一个要被读取的字节索引号为0” this.pos = 0; // 初始化“字节流的长度为buf的长度” this.count = buf.length; } // 构造函数:建立一个内容为buf的字节流,而且是从offset开始读取数据,读取的长度为length public ByteArrayInputStream(byte buf[], int offset, int length) { // 初始化“字节流对应的字节数组为buf” this.buf = buf; // 初始化“下一个要被读取的字节索引号为offset” 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; } // 将“字节流的数据写入到字节数组b中” // off是“字节数组b的偏移地址”,表示从数组b的off开始写入数据 // len是“写入的字节长度” 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; } // 跳过“字节流”中的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; } // 保存当前位置。readAheadLimit在此处没有任何实际意义 public void mark(int readAheadLimit) { mark = pos; } // 重置“字节流的读取索引”为“mark所标记的位置” public synchronized void reset() { pos = mark; } public void close() throws IOException { } }