Java 如何正确使用ByteBuffer?
我正在尝试正确地使用ByteBuffer和BigEndian字节顺序格式 在将其存储到Cassandra数据库之前,我尝试将两个字段合并到一个ByteBuffer中 我将要写入Cassandra的字节数组由三个字节数组组成,如下所述-Java 如何正确使用ByteBuffer?,java,bytearray,bytebuffer,endianness,Java,Bytearray,Bytebuffer,Endianness,我正在尝试正确地使用ByteBuffer和BigEndian字节顺序格式 在将其存储到Cassandra数据库之前,我尝试将两个字段合并到一个ByteBuffer中 我将要写入Cassandra的字节数组由三个字节数组组成,如下所述- short employeeId = 32767; long lastModifiedDate = "1379811105109L"; byte[] attributeValue = os.toByteArray(); 现在,我将编写employeeId, >
short employeeId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] attributeValue = os.toByteArray();
现在,我将编写employeeId
,<代码> > ListMexFieldDe< <代码> >代码>属性值一起成为一个字节数组,然后生成的字节数组i将写入卡桑德拉,然后我将拥有我的C++程序,该程序将从卡桑德拉检索该字节数组数据,然后反序列化它以提取<代码> EnvieID ID/COD>lastModifiedDate
和它的attributeValue
为了做到这一点,我使用了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的正确方法吗?默认顺序始终是BIG_ENDIAN,因此您不需要设置它。另外,当wrap()已被倒带()时 我不会复制底层数组,而是使用底层数组 替换
bbuf.rewind();
// best approach is copy the internal buffer
byte[] bytesToStore = new byte[size];
bbuf.get(bytesToStore);
与
你希望Cassandra如何确定
attributeValue
数组的长度?@AlexeiKaigorodov:我不确定,我理解你的问题。。cassandra是否需要确定attributeValue数组的长度?我们只需要把它存起来然后取回就行了?:非常感谢彼得。。我一定会做出那些改变。。。还有什么你认为不对的吗?还是你想让我改进?感谢您的帮助。您可以使用直接ByteBuffer来提高性能,而不是使用byte[]和heap ByteBuffer。很抱歉,我弄糊涂了。。你能提供一个例子如何在我的代码的基础上做到这一点吗?谢谢。@TechGeeky除非Cassandra支持直接缓冲区,否则我不会费心,因为它不会有帮助。我不确定这一点,但我想现在可以了。。还有一件事,反序列化部分呢?我们也需要做些改变吗?或者反序列化部分看起来不错。?谢谢
byte[] bytesToStore = bbuf.array();