4.3中的Copy方法下为什么要有while?
while(((b=in.read(buf,0,buf.length))!=-1))
{
out.write(buf,0,b);
}
++++++++++++++
能不能像下面这样》
b=in.read(buf,0,buf.length);
out.write(buf,0,b);
out.flush();//最好加上
while(((b=in.read(buf,0,buf.length))!=-1))
{
out.write(buf,0,b);
}
++++++++++++++
能不能像下面这样》
b=in.read(buf,0,buf.length);
out.write(buf,0,b);
out.flush();//最好加上
2017-01-09
这是底层实现代码,我把主要的注释写出来了。自己看着来,不清楚就再探究下。
public synchronized int read(byte b[], int off, int len)
throws IOException
{
getBufIfOpen(); // Check for closed stream
if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int n = 0;
for (;;) {
int nread = read1(b, off + n, len - n); //关键,调用read1,达到不重复读的目的
if (nread <= 0)
return (n == 0) ? nread : n;
n += nread;
if (n >= len)
return n;
// if not closed but no bytes available, return
InputStream input = in;
if (input != null && input.available() <= 0)
return n;
}
}
private int read1(byte[] b, int off, int len) throws IOException {
int avail = count - pos;
if (avail <= 0) {
/* If the requested length is at least as large as the buffer, and
if there is no mark/reset activity, do not bother to copy the
bytes into the local buffer. In this way buffered streams will
cascade harmlessly. */
if (len >= getBufIfOpen().length && markpos < 0) {
return getInIfOpen().read(b, off, len);
}
fill();
avail = count - pos;
if (avail <= 0) return -1;
}
int cnt = (avail < len) ? avail : len;
System.arraycopy(getBufIfOpen(), pos, b, off, cnt); //读取范围,pos变量是关键
pos += cnt; //关键所在,pos变量是成员变量,会被记录,这也是为什么不会重复读
return cnt;
}
举报