有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    将数组转换为字节数组,然后发送字节数组。接收器将字节数组转换回int[]

    可以使用类DataOutputStream创建字节数组

     ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);
        int len = 0;
        in protokollVersion = 1;
        // Write a version, in case you want to change your format later, such that 
        // the receiver has a chance to detect which format version is used.
        dos.writeInt(protokollVersion);
        if (arr != null) {
          len = arr.length;
        }
        dos.writeInt(arr.length);
        for (int i = 0; i  < len; i++) {
            dos.writeInt(arr[i]);
        }
        dos.close();
        byte[] bytes = bos.getBytes();
    

    在接收器端,使用DataInputStream(byte[] bytes)DataInputStream.readInt()读取字节数组