早上好。 我需要在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进行编码,使其等于原始字符串(按值相等)?
非常感谢
答案 0 :(得分:1)
这是你如何做到的。请注意,它工作正常,因为String是你写的最后一件事,所以你知道它从最后一次写入的字符串到缓冲区的最后写入位置。如果它在中间,你必须以某种方式写字符串的长度,以便能够知道要读取多少字节。
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);