在 ByteBuffer 中写入混合数据类型

Writing mixed data type in a ByteBuffer

早上好。 我需要在 ByteBuffer 中存储以下格式的数据。 然后存储此 ByteBuffer 并稍后打印到控制台。

数据格式:

10:30             [2]                 This is my message to you.
IntCharInt  Char  CharIntChar  Char   String

存储部分看起来很简单。

ByteBuffer buff = ByteBuffer.allocate(100);

buffer.putInt(10).putChar(':').putInt(30).putChar(' ');
buffer.putChar('[').putInt(2).putChar(']').putChar(' ');
buffer.put("This is my message to you.".getBytes());

我可以通过以下方式检索底层字节数组:

byte[] bArray = buff.array( );

如何对字符串中的 bArray 进行编码,使其等于原始字符串(按值相等)?

非常感谢

以下是您的操作方法。请注意,它工作正常,因为字符串是您最后写入的内容,因此您知道它从最后写入的字符之后到缓冲区的最后写入位置。如果它在中间,您将不得不以某种方式写出字符串的长度才能知道要读取多少字节。

    ByteBuffer buffer = ByteBuffer.allocate(100);

    buffer.putInt(10).putChar(':').putInt(30).putChar(' ');
    buffer.putChar('[').putInt(2).putChar(']').putChar(' ');

    // use a well-defined charset rather than the default one, 
    // which varies from platform to platform
    buffer.put("This is my message to you.".getBytes(StandardCharsets.UTF_8));

    // go back to the beginning of the buffer
    buffer.flip();

    // get all the bytes that have actually been written to the buffer
    byte[] bArray = new byte[buffer.remaining()];
    buffer.get(bArray);

    // recreate a buffer wrapping the saved byte array
    buffer = ByteBuffer.wrap(bArray);
    String original =
        new StringBuilder()
            .append(buffer.getInt())
            .append(buffer.getChar())
            .append(buffer.getInt())
            .append(buffer.getChar())
            .append(buffer.getChar())
            .append(buffer.getInt())
            .append(buffer.getChar())
            .append(buffer.getChar())
            .append(new String(buffer.array(), buffer.position(), buffer.remaining(), StandardCharsets.UTF_8))
            .toString();
    System.out.println("original = " + original);