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循环就是为了读取完要读取的东西。同时也像你说的为了防止它为空。而且,按照正常情况,buf是字节数组,应该是1024字节的倍数吧,有时候一次读不完,所以用个while循环来判定。
望采纳,谢谢。
这是底层实现代码,我把主要的注释写出来了。自己看着来,不清楚就再探究下。
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;
}
我的意思是既然out.write(buf,0,b);已经把数据都写进去了,为什么之前还要有while?