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
舉報
2017-01-09
這個while循環(huán)就是為了讀取完要讀取的東西。同時也像你說的為了防止它為空。而且,按照正常情況,buf是字節(jié)數組,應該是1024字節(jié)的倍數吧,有時候一次讀不完,所以用個while循環(huán)來判定。
望采納,謝謝。
2017-01-21
這是底層實現代碼,我把主要的注釋寫出來了。自己看著來,不清楚就再探究下。
?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;
? ? }
2017-01-09
我的意思是既然out.write(buf,0,b);已經把數據都寫進去了,為什么之前還要有while?