标签:des style java color strong 文件
public int read(byte[] b, int off, int len) throws IOException
len
个数据字节读入字节数组。尝试读取多达 len
字节,但可能读取较少数量。以整数形式返回实际读取的字节数。
在输入数据可用、检测到流的末尾或者抛出异常前,此方法一直阻塞。
如果 b
为 null
,则抛出 NullPointerException
。
如果 off
为负,或 len
为负,或 off+len
大于数组 b
的长度,则抛出 IndexOutOfBoundsException
。
如果 len
为 0,则没有字节可读且返回 0
;否则,要尝试读取至少一个字节。如果因为流位于文件末尾而没有可用的字节,则返回值 -1
;否则,至少可以读取一个字节并将其存储在 b
中。
将读取的第一个字节存储在元素 b[off]
中,下一个存储在 b[off+1]
中,依次类推。读取的字节数最多等于 len
。让 k 为实际读取的字节数;这些字节将存储在元素 b[off]
至 b[off+
k-1]
之间,其余元素 b[off+
k]
至 b[off+len-1]
不受影响。
在任何情况下,元素 b[0]
至 b[off]
和元素 b[off+len]
至 b[b.length-1]
都不会受到影响。
如果不是因为流位于文件末尾而无法读取第一个字节,则抛出 IOException
。特别是,如果输入流已关闭,则抛出 IOException
。
类 InputStream
的 read(b,
off,
len)
方法只重复调用方法 read()
。如果第一个这样的调用导致 IOException
,则从对 read(b,
off,
len)
方法的调用中返回该异常。如果对 read()
的任何后续调用导致 IOException
,则该异常会被捕获并将发生异常时的位置视为文件的末尾;到达该点时读取的字节存储在 b
中并返回发生异常之前读取的字节数。建议让子类提供此方法的更有效的实现。
b
- 读入数据的缓冲区。off
- 在其处写入数据的数组 b
的初始偏移量。len
- 要读取的最大字节数。-1
。IOException
- 如果发生 I/O 错误。NullPointerException
- 如果 b
为 null
。
read是一个很好的读取器,对流,如应用于下载中是一个不错的算法!例子:
public static final int INITIAL_SIZE = 100000;
private byte buffer[] = new byte[INITIAL_SIZE];
private int index = 0;
private int capacity() {
return (buffer.length - index);
}
public void read(InputStream in, int max) throws IOException {
long k= 0;
do {
int size;
// only read up to the max size, if the max size was
// specified
if (max != -1) {
size = Math.min(capacity(), max);
} else {
size = capacity();
}
// actually read the block
k= in.read(buffer, index, capacity());
// quit if we hit EOF
if (k< 0) {
break;
}
// adjust capacity if needed
index += k;
if (capacity() < 10) {
expand();
}
// see if we hit the max length
if (max != -1) {
max -= l;
if (max <= 0) {
break;
}
}
} while (k!= 0);
}
基于java的InputStream.read(byte[] b,int off,int len)算法学习,布布扣,bubuko.com
基于java的InputStream.read(byte[] b,int off,int len)算法学习
标签:des style java color strong 文件
原文地址:http://www.cnblogs.com/moonfans/p/3837748.html