您對read()這個方法的重載版本可能不是非常了解.
給您看看read()方法的幾個定義:
當read()方法沒有參數(shù)時,即循環(huán)是:while((b=in.read())!=-1).
此時的read()方法的定義是:
Reads a byte of data from this input stream. This method blocks if no input is yet available.
從輸入流讀取一個字節(jié)的數(shù)據(jù),如果沒有輸入,則此方法結束.
返回值為:
the next byte of data, or -1 if the end of the file is reached.
輸入流中的下一個字節(jié).或者在讀取到文件結尾(EOF)時返回-1.
那什么情況下b是讀取到的字節(jié)的個數(shù)呢?這種形式:while((b=in.read(buf,0,buf.length))!=-1)
此時read()方法的重載函數(shù)定義為:
Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.
從該輸入流讀取最多l(xiāng)en個字節(jié)到字節(jié)數(shù)組中,如果讀取到的字節(jié)不是0個.則保存到緩沖區(qū)中直到刷新緩沖區(qū).否則不讀取字節(jié)返回0.
這個read(byte[]b,int off,int len)方法的返回值為:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
返回讀取到緩沖區(qū)的字節(jié)的總數(shù),或者在到達文件結尾時返回-1.
綜上所述,在read()方法無參數(shù)時返回讀取到的一個字節(jié),在參數(shù)為read(byte[]b,int off,int len)時返回讀取到的字節(jié)數(shù)量,而不是您認為的b一直是得到讀取的字節(jié)數(shù)量.
2018-07-08
您說的是in是什么類型的呢,F(xiàn)ileInputStream?在FileInputStream的read()方法中有返回值為int類型的重載函數(shù).
2022-03-25
nbsp;nbsp;nbsp;nbsp;謝謝老師們!您好,現(xiàn)在json和xml做為通信格式都在使用,要看業(yè)務,json其實很受開發(fā)者喜歡,喜歡他比較簡單,生成和解析json都很方便,但這個要看個人。祝學習愉快!