我需要使用Java代码将Byte Array
值写入Cassandra。然后,我将拥有我的C++程序,它将从Cassandra中检索字节数组数据,然后将其反序列化。如何使用字节缓冲区序列化字节数组以开始遵循Big Endian格式?
即字节数组,我将被写入到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++代码时可以简化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的东西吗?谢谢..
我可能会mising约字节缓冲这里微小的细节,因为这是我第一次使用它..
- 首先,我应该在这里使用ByteByffer都在我用例?
- 其次,如果是,那么在我的用例中使用它的最佳方式是什么...?
,我想要确保的是,我正在写正确成卡桑德拉按照大Endians字节顺序格式,以便于C++的一面,我没有遇到任何问题都没有,而反序列化字节的唯一的事Array ...
感谢JoaoHenriques的建议...在你的例子中,你能告诉我你是如何计算大小的? )'做和可以使用它的优点是什么?感谢您的帮助.. – ferhan
我已经编辑代码,以解释如何获得缓冲区的大小。字节缓冲区有一个内部字节指针,通知哪个字节读/写接下来,做回退会使指针指向零[与bbuf.position(0)相同]。每次操作都会使该指针增加操作所消耗的大小。例如,getInt()读取4个字节并增加指针通过4. putInt()也是一样,写入4个字节并将其增加4个。 –
感谢您的编辑..是的,它清除了我所有的疑惑。我最后一个问题是 - 反序列化时,您没有在任何地方使用'attributeValueLen'?我们应该在某个地方使用它吗?而你错过了错误?或者它是多余的? – ferhan