您的位置:首页 > 其它

ByteArrayInputStream 和InputStream中read方法

2016-02-16 14:19 507 查看
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.这样可以在读取较多字节的时候提高处理效率






                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: