我有一個字節數組byteObj
它由BSON序列化。與string.getBytes混淆()
String strObj = new String(byteObj)
System.out.println(byteObj.length)
System.out.println(strObj.getBytes().length)
結果是152
和154
。而這兩個字節數組並不相同。如何從字符串中恢復原始的bson字節數組?
更新:
152 154
[-104, 0, 0, 0, 4, 116, 105, 116, 108, 101, 0, 80, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 3, 0, 0, 0, 105, 115, 0, 2, 50, 0, 2, 0, 0, 0, 97, 0, 2, 51, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 52, 0, 2, 0, 0, 0, 97, 0, 2, 53, 0, 3, 0, 0, 0, 105, 115, 0, 2, 54, 0, 6, 0, 0, 0, 116, 105, 116, 108, 101, 0, 0, 4, 99, 111, 110, 116, 101, 110, 116, 0, 51, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 2, 0, 0, 0, 97, 0, 2, 50, 0, 8, 0, 0, 0, 99, 111, 110, 116, 101, 110, 116, 0, 2, 51, 0, 3, 0, 0, 0, 105, 115, 0, 0, 0]
[-17, -65, -67, 0, 0, 0, 4, 116, 105, 116, 108, 101, 0, 80, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 3, 0, 0, 0, 105, 115, 0, 2, 50, 0, 2, 0, 0, 0, 97, 0, 2, 51, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 52, 0, 2, 0, 0, 0, 97, 0, 2, 53, 0, 3, 0, 0, 0, 105, 115, 0, 2, 54, 0, 6, 0, 0, 0, 116, 105, 116, 108, 101, 0, 0, 4, 99, 111, 110, 116, 101, 110, 116, 0, 51, 0, 0, 0, 2, 48, 0, 5, 0, 0, 0, 116, 104, 105, 115, 0, 2, 49, 0, 2, 0, 0, 0, 97, 0, 2, 50, 0, 8, 0, 0, 0, 99, 111, 110, 116, 101, 110, 116, 0, 2, 51, 0, 3, 0, 0, 0, 105, 115, 0, 0, 0]
首先是BSON字節數組。
更新2: 測試代碼
BSONObject ob = new BasicBSONObject()
.append("title", Arrays.asList(new String[]{"this", "is", "a", "this", "a", "is", "title"}))
.append("content", Arrays.asList(new String[]{"this", "a", "content", "is"}));
byte[] ahaha = BSON.encode(ob);
BSON.decode(ahaha);
// BSON.decode(new String(ahaha).getBytes());
byte[] strByte = new String(ahaha).getBytes();
System.out.println(ahaha.length + "\t" + strByte.length);
System.out.println(Arrays.toString(ahaha));
System.out.println(Arrays.toString(strByte));
二進制數據轉換爲字符串,並且反之亦然的溶液見How do you convert binary data to Strings and back in Java?。
你原來byteObj陣列應該是長度154 ... – assylias
你確定你Byte數組是文本?我的意思是,也許字節數組是一個圖像,字節不能轉換爲字符串中的有效字符:這就是爲什麼你有一個長度的差異。 – romfret
任何此投票的理由?你甚至可以理解這個問題嗎? – Tilney