0

我正在尝试使用 BigEndian 字节顺序格式正确使用 ByteBuffer ..

在将其存储在 Cassandra 数据库中之前,我尝试将几个字段组合到一个 ByteBuffer 中。

我将写入 Cassandra 的字节数组由三个字节数组组成,如下所述 -

short employeeId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] attributeValue = os.toByteArray();

现在,我将employeeId,lastModifiedDateattributeValue一起写入单个字节数组,然后将生成的字节数组写入 Cassandra,然后我将拥有我的 C++ 程序,该程序将从 Cassandra 检索该字节数组数据,然后将其反序列化以提取employeeId,lastModifiedDateattributeValue从中提取它。

所以要做到这一点,我使用 ByteBuffer 和 BigEndian 字节顺序格式。

我已经把这段代码放在一起了——

public static void main(String[] args) throws Exception {

        String text = "Byte Buffer Test";
        byte[] attributeValue = text.getBytes();

        long lastModifiedDate = 1289811105109L;
        short employeeId = 32767;

        int size = 2 + 8 + 4 + attributeValue.length; // short is 2 bytes, long 8 and int 4

        ByteBuffer bbuf = ByteBuffer.allocate(size); 

        bbuf.order(ByteOrder.BIG_ENDIAN);
        bbuf.putShort(employeeId);
        bbuf.putLong(lastModifiedDate);
        bbuf.putInt(attributeValue.length);
        bbuf.put(attributeValue);

        bbuf.rewind();

        // best approach is copy the internal buffer
        byte[] bytesToStore = new byte[size];
        bbuf.get(bytesToStore);

        // write bytesToStore in Cassandra...

        // Now retrieve the Byte Array data from Cassandra and deserialize it...
        byte[] allWrittenBytesTest = bytesToStore;//magicFunctionToRetrieveDataFromCassandra();

        ByteBuffer bb = ByteBuffer.wrap(allWrittenBytesTest);

        bb.order(ByteOrder.BIG_ENDIAN);
        bb.rewind();

        short extractEmployeeId = bb.getShort();
        long extractLastModifiedDate = bb.getLong();
        int extractAttributeValueLength = bb.getInt();
        byte[] extractAttributeValue = new byte[extractAttributeValueLength];

        bb.get(extractAttributeValue); // read attributeValue from the remaining buffer

        System.out.println(extractEmployeeId);
        System.out.println(extractLastModifiedDate);
        System.out.println(new String(extractAttributeValue));

}

有没有更好的方法来做到这一点,就像我目前正在做的那样?或者我们可以在这里做一些小的改进?

这是我第一次使用 ByteBuffer 所以有一点问题......

谁能看看,让我知道这是否是使用 ByteBuffer 的正确方法?

4

1 回答 1

1

默认顺序始终为 BIG_ENDIAN,因此您不必设置它。此外,当您 wrap() 时已经 rewind() 了。

我不会复制底层数组,而是使用底层数组。

代替

    bbuf.rewind();

    // best approach is copy the internal buffer
    byte[] bytesToStore = new byte[size];
    bbuf.get(bytesToStore);

    byte[] bytesToStore = bbuf.array();
于 2013-10-11T07:56:32.673 回答