InputStream读取方法可能返回短读取;您必须检查返回值以确定已读取的字符数,并继续循环读取直到获得所需的数字。该方法可能会阻塞,但是只会阻塞直到
某些 数据可用(不一定是您请求的所有数据)可用为止。
大多数人最终都会编写一个“ readFully”方法,例如DataInputStream,该方法读取预期的数据量或引发IOException:
static public int readFully(InputStream inp, byte[] arr, int ofs, int len) throws IOException { intrmn,cnt; for(rmn=len; rmn>0; ofs+=cnt, rmn-=cnt) { if((cnt=inp.read(arr,ofs,rmn))==-1) { throw new IOException("End of stream encountered before reading at least "+len+" bytes from input stream"); } } return len; }


