我需要使用 Java 代码将 Byte Array
值写入 Cassandra。然后我将使用我的 C++ 程序从 Cassandra 检索字节数组数据,然后反序列化它。
我将写入 Cassandra 的字节数组由三个字节数组组成,如下所述 -
short employeeId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] attributeValue = os.toByteArray();
现在,我将把 employeeId
、 lastModifiedDate
和 attributeValue
一起写入单个字节数组,并将生成的字节数组写入 Cassandra然后我将使用我的 C++ 程序从 Cassandra 检索字节数组数据,然后反序列化它以提取 employeeId
、 lastModifiedDate
和 attributeValue
来自它。
我不确定在写入 Cassandra 时是否应该在 Java 代码中使用 Big Endian,以便在读回 C++ 代码时得到简化?
我在Java端进行了尝试,以确保它遵循某种格式(Big Endian),同时将所有内容写入单个字节数组,然后这个字节数组也将被写回Cassandra,但不确定这是否是这样对还是不对?
public static void main(String[] args) throws Exception {
String os = "Byte Array Test";
byte[] attributeValue = os.getBytes();
long lastModifiedDate = 1379811105109L;
short employeeId = 32767;
ByteArrayOutputStream byteOsTest = new ByteArrayOutputStream();
DataOutputStream outTest = new DataOutputStream(byteOsTest);
// merging everything into one Byte Array here
outTest.writeShort(employeeId);
outTest.writeLong(lastModifiedDate);
outTest.writeInt(attributeValue.length);
outTest.write(attributeValue);
byte[] allWrittenBytesTest = byteOsTest.toByteArray();
// initially I was writing allWrittenBytesTest into Cassandra...
ByteBuffer bb = ByteBuffer.wrap(allWrittenBytesTest).order(ByteOrder.BIG_ENDIAN);
// now what value I should write into Cassandra?
// or does this even looks right?
// And now how to deserialize it?
}
有人可以帮我解决这个 ByteBuffer 问题吗?谢谢..
我可能会在这里错过有关字节缓冲区的详细信息,因为这是我第一次使用它..
- 首先,我是否应该在我的用例中使用 ByteByffer?
- 其次,如果是,那么在我的用例中使用它的最佳方式是什么......?
我想要确保的唯一一件事是,我按照 Big-Endians 字节顺序格式正确写入 Cassandra,这样在 C++ 方面,我在反序列化该字节数组时根本不会遇到任何问题。 .
最佳答案
不要手动序列化 Thrift 的 ByteBuffer,而是使用 Cassandra 的 native CQL 驱动程序:http://github.com/datastax/java-driver
关于java - 如何使用字节缓冲区序列化字节数组以开始遵循 Big Endian 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19126764/