InputStream:
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; }
ByteArrayInputStream:
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; }总结:两个方法都是 对于in 中的buff[]的读取,从已经读取的pos的位置开始读,读取len长度的byte[] 到b[]的off 到 off+len的位置,如果off+len超过了buff[]中从pos能够读取的最大字节数(count-pos),那么后面的就不再读取,在inputStream 的抽象类中的处理方式是,调用子类的read()方法,pos++的递增,超过了就break;
在ByteArrayInputStream 中的处理方式是,len超过了直接减小len的值,然后调用System.arraycopy来给b[]赋值,最后pos移动到已经读取了len的位置也就是pos+len.这样可以在读取较多字节的时候提高处理效率