java socket接收保证能读完数据的方法

本文介绍了一种用于从 Java 的 InputStream 中读取字节数据到 byte 数组的方法。该方法通过循环调用 InputStream 的 read 方法确保所有数据都被正确读取,直到读取长度等于指定长度为止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


//    private static byte[] readData(InputStream in,byte[] bData) throws IOException{
//      int readLength = in.read(bData);
//      if(readLength!=bData.length){
//          byte[] temp2 = readData(in,new byte[bData.length-readLength]);
//          System.arraycopy(temp2, 0, bData, readLength, temp2.length);
//          return bData;
//      }else{
//          return bData;
//      }
//    }

//    private static void readData(InputStream in,byte[] bData) throws IOException{
//      readData(in,bData,0,bData.length);
//    }

//    private static void readData(InputStream in,byte[] bData,int off,int length) throws IOException{
//      int readLength = in.read(bData, off, length);
//      if(readLength!=length){
//          readData(in,bData,readLength+off,length-readLength);
//      }
//    }

//    private static void readData(InputStream in,byte[] bData,int off,int length) throws IOException{
//
//      while(true){
//          int readLength = in.read(bData, off, length);
//          if(readLength!=length){
//              off = readLength+off;
//              length = length-readLength;
//          }else{
//              break;
//          }
//      }
//    }

//    private static void readData(InputStream in,byte[] bData,int off,int length) throws IOException{
//      int readLength = 0;
//      do{
//          off = readLength+off;
//          length = length-readLength;
//          readLength = in.read(bData, off, length);
//      }while(readLength!=length);
//    }

    /**
     * 最终使用此方法
     * @param in  输入流
         * @param bData  读取数据
     * @throws IOException  
     */
    private static void readData(InputStream in,byte[] bData) throws IOException{
        int off = 0;
        int length = bData.length;
        int readLength = 0;
        do{
            off = readLength+off;
            length = length-readLength;
            readLength = in.read(bData, off, length);
        }while(readLength!=length);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值