您對read()這個方法的重載版本可能不是非常了解.
給您看看read()方法的幾個定義:
當read()方法沒有參數時,即循環是:while((b=in.read())!=-1).
此時的read()方法的定義是:
Reads a byte of data from this input stream. This method blocks if no input is yet available.
從輸入流讀取一個字節的數據,如果沒有輸入,則此方法結束.
返回值為:
the next byte of data, or -1 if the end of the file is reached.
輸入流中的下一個字節.或者在讀取到文件結尾(EOF)時返回-1.
那什么情況下b是讀取到的字節的個數呢?這種形式:while((b=in.read(buf,0,buf.length))!=-1)
此時read()方法的重載函數定義為:
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.
從該輸入流讀取最多len個字節到字節數組中,如果讀取到的字節不是0個.則保存到緩沖區中直到刷新緩沖區.否則不讀取字節返回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.
返回讀取到緩沖區的字節的總數,或者在到達文件結尾時返回-1.
綜上所述,在read()方法無參數時返回讀取到的一個字節,在參數為read(byte[]b,int off,int len)時返回讀取到的字節數量,而不是您認為的b一直是得到讀取的字節數量.
2018-07-08
您說的是in是什么類型的呢,FileInputStream?在FileInputStream的read()方法中有返回值為int類型的重載函數.
2022-03-25
nbsp;nbsp;nbsp;nbsp;謝謝老師們!您好,現在json和xml做為通信格式都在使用,要看業務,json其實很受開發者喜歡,喜歡他比較簡單,生成和解析json都很方便,但這個要看個人。祝學習愉快!