ByteBuffer를 BigEndian 바이트 순서 형식으로 올바르게 사용하려고합니다.ByteBuffer를 올바르게 사용하는 방법은 무엇입니까?
저는 Cassandra 데이터베이스에 저장하기 전에 하나의 ByteBuffer에 두 필드를 조합하려고합니다. 지금
short employeeId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] attributeValue = os.toByteArray();
below- 바와 같이 I 카산드라으로 작성한다
그 바이트 어레이 I 단일 바이트 배열 것을 함께 employeeId
, lastModifiedDate
및 attributeValue
물품 것이다 세 바이트 배열로 구성되는 결과 바이트 배열 내가 카산드라에 쓸 것입니다 그리고 난 그 Cassandra에서 그 바이트 배열 데이터를 검색하고 employeeId
, lastModifiedDate
및 attributeValue
을 추출 deserialize 내 C + + 프로그램을 가지고있을 것입니다.
이렇게하려면 BigEndian 바이트 순서 형식으로 ByteBuffer를 사용하고 있습니다. ,
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를 사용하는 올바른 방법인지 알려 수 있습니까?
와
교체? –
@AlexeiKaigorodov : 확실치 않습니다. 귀하의 질문을 이해합니다. cassandra가 attributeValue 배열의 길이를 결정해야합니까? 우리는 그것을 저장하고 검색해야합니다. – ferhan