我有一个字节数组并使用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 之类的