Java equivalent of Python's struct.pack?

后端 未结 4 1056
天涯浪人
天涯浪人 2020-12-10 11:43

Is there any function equivalent to Python\'s struct.pack in Java that allows me to pack and unpack values like this?

pump_on = struct.pack(\"II         


        
4条回答
  •  生来不讨喜
    2020-12-10 11:46

    Something like this:

    final ByteArrayOutputStream data = new ByteArrayOutputStream();
    final DataOutputStream stream = new DataOutputStream(data);
    stream.writeUTF(name);
    stream.writeUTF(password);
    final byte[] bytes = stream.toByteArray(); // there you go
    

    Later, you can read that data:

    final DataInputStream stream = new DataInputStream(
      new ByteArrayInputStream(bytes)
    );
    final String user = stream.readUTF();
    final String password = stream.readUTF();
    

提交回复
热议问题