2012-10-09 46 views
2

我有一個字節數組,並使用new String(array)從它創建字符串。當我使用.getBytes()將它轉換回字節數組時,它不會返回原始字節數組。是什麼賦予了?無法從字符串取回原始字節數組

String text = "two hats"; 
boolean t1 = Arrays.equals(text.getBytes(), text); // true 

byte[] barray = {(byte)0x8f, (byte)0xd5, (byte)0xaf, (byte)0x30, (byte)0xb9};   

String test1 = new String(barray); 
boolean t2 = Arrays.equals(barray.getBytes(), test1); // false 

// I tried setting an encoding but that didn't help. 

Charset cs = Charset.forName("UTF-8"); 
String test2 = new String(barray, cs);  
boolean t3 = Arrays.equals(barray, test2, cs); // false 

這是我實際使用的代碼。

// test byte array vs string 
public static void testEqual(byte[] bytes, String str) { 
    byte[] fromString = str.getBytes();   

    printBytes(bytes);   
    printBytes(fromString);   
    System.out.println(Arrays.equals(bytes, fromString));   
} 

// test byte array vs string, with charset 
public static void testEqual(byte[] bytes, String str, Charset charset) { 
    byte[] fromString = str.getBytes(charset);   

    printBytes(bytes);   
    printBytes(fromString);   
    System.out.println(Arrays.equals(bytes, fromString)); 
} 

// prints bytes as hex string 
public static void printBytes(byte[] bytes) { 
    for (byte b: bytes) { 
     System.out.print(String.format("%02X ", b)); 
    }   
    System.out.println(); 
} 

public static void main(String[] args) { 
    String text = "two hats"; 
    testEqual(text.getBytes(), text); // works fine 

    byte[] barray = {(byte)0x8f, (byte)0xd5, (byte)0xaf, (byte)0x30, (byte)0xb9};   

    String test1 = new String(barray); // breaks  
    testEqual(barray, test1); 

    Charset cs = Charset.forName("UTF-8"); // breaks too 
    String test2 = new String(barray, cs);  
    testEqual(barray, test2, cs); 
} 

演示:http://ideone.com/IRHlb

PS:我不希望使用Base64編碼或諸如此類

回答

4

你似乎是試圖存儲任意的二進制數據通過將其轉換爲字符串使用平臺默認編碼。不要這樣做。使用base64或hex來表示任意二進制數據爲文本。有很多base64轉換類;我喜歡this public domain one

如果數據真的一些文本的二進制編碼形式,你應該明確指定編碼 - 但這僅如果原始數據是文本爲宜。 (使用平臺的默認編碼幾乎是總是不好主意。)

二進制數據和文本數據有很大的不同。任意將不透明的二進制數據轉換爲字符串就像是希望能夠將任意文件加載到圖像編輯器中,並看到有用的東西。

+0

爲什麼這是一個問題?我期望字符串本質上是一個字節數組。 – quantumSoup

+0

@quantumSoup:他們不是。他們的序列*字符*。他們是*文本*數據。如果要將* binary *數據表示爲* text *,則需要執行適當的轉換。 –

+0

我最初反對將它編碼爲文本,因爲它總是帶來一些開銷。像base64這樣的33%似乎是過度的。 – quantumSoup

相關問題