已知数据长度为20字节,下面两种方法那一个比较可靠?
方法一: private byte[] readData(InputStream is) throws IOException{
try{
byte[] buff = new byte[20];
is.read(buff, 0, 20);
return buff;
}catch(Exception e){

}
throw new IOException();

}
方法二: private static byte[] readData(InputStream is) throws IOException{
byte[] buff = new byte[20];
int totalSize = 0;
int readSize = 0;
while ((readSize = is.read(buff, totalSize, 20 - totalSize)) != -1) {
totalSize = totalSize + readSize;
if (totalSize == 20) {
return buff;
}
}
throw new IOException();

}

解决方案 »

  1.   


    我对流操作不是特别了解,我知道is.read(buff, 0, 20);如果buff没有写满20个字节,是不是还可从流里继续读。所以我想出了第二种方法。
      

  2.   

    试试这个,最多只需要一次。
    private byte[] readData(InputStream is) throws IOException{
    int maxLen = 20;
    byte[] result = new byte[maxLen];
            byte[] buff = new byte[maxLen];
            try{
            int len = is.read(buff, 0, maxLen);
            if(len == maxLen){
             return buff;
            }
            //已经读取的长度
            int readLen = 0;
            while(len>-1){
             if(readLen+len>maxLen){
             len = maxLen-readLen;
             }
             System.arraycopy(buff, 0, result, readLen, len);
             readLen+=len;
             if(readLen>=maxLen){
             break;
             }else{
             len = is.read(buff, 0, maxLen);
             }
            }            
            }finally{
             buff = null;
            }
            return buff;
        }