(len = is.read(buffer)) != -1的原理详解
InputStream.read(buffer) 方法
- 在java中api文档有read()这几种方法
方法摘要 | 方法 | 作用 |
---|---|---|
abstract int | read() | 从输入流中读取数据的下一个字节 |
int | read(byte[] b) | 将输入流中读取一定数量 并将其存储在缓冲区数组 b 中。 |
int | read(byte[] b, int off, int len) | 将输入流中最多 len 个数据字节读入 byte 数组。 |
2.read()==-1的含义
/**
* Reads the next byte of data from the input stream. The value byte is * returned as an <code>int</code> in the range <code>0</code> to * <code>255</code>. If no byte is available because the end of the stream * has been reached, the value <code>-1</code> is returned. This method * blocks until input data is available, the end of the stream is detected, * or an exception is thrown.
* * <p> A subclass must provide an implementation of this method.
* * @return the next byte of data, or <code>-1</code> if the end of the * stream is reached.
* @exception IOException if an I/O error occurs.
*/
这是read()方法中的注释,意识就是read()从输入流中读取下一个字节。如果没有字节可读(也就是read()读到文件最后了)read()返回-1.
- 从源码理解
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
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;
}
流程:
-
如何判断文件读取完成?
若我们下载一个文件,要在读取中不断的获取read()的返回值,判断何时-1,来表示读取完成。
-
为何不使用read(),而是用read(buffer)?
原因是:read(buffer)效率更高,如果文件有10000byte,使用read()要读10000次然后不停的往存储上写入,而使用read(buffer) 可以读取最大buffer长度的数据(如:buffer长度1000),只需11次(为何11次而不是10,请接着看),然后写入存储中。
-
read(buffer)如何读入?
如10000byte的文件下载,我们buffer长度1000,read(buffer)其实可以看做,是将文件分成【(10000除以1000 向上取整)+1 份】11份,其中最后一块其实就是个空的,用来判断文件读取完成。
根据上面的源码,我们知道其实是read(buffer) 里面调用 read(byte b[], int off, int len), 在 read(byte b[], int off, int len) 中,读取文件
- 首先
,在每个段中,使用
int c = read();
if (c == -1) {
return -1;
}
判断第一个字节是否是-1. c==-1,说明当前是上面的1所指的第11块。
- 其次
如果c!=-1,说明文件未读取完成(也就是1-10块),for循环
for (; i < len ; i++) {
c = read();
if (c == -1) {
break;
}
b[off + i] = (byte)c;
不断地读取字节,如果在读取期间c==-1.说明文件读取完成(也就是第10块,第10块写入的byte长度,不一定都填充满buffer的长度1000),此时,break,跳出循环。进行下一个read(buffer) ,此时满足上面的if,返回-1。