2013-09-05 39 views
0

我有一个爪哇 - 字节的字符串到字节[]

String b = "[[email protected]"; 

这是字节[]输出,我存储在一个字符串

现在我想将其转换回字节[ ]

byte[] c = b.getBytes(); 

,但它给了我不同的字节是

[[email protected] 

我该如何取回[B @ 64964f8e?

+4

:)阅读上的'的toString()'方法是什么。 –

+0

特别是''[B @ 64964f8e''字符串几乎肯定没有实际值。 –

+0

您是如何第一次在字符串中存储字节的?请添加该代码以便更好地理解 –

回答

1
String b = "[[email protected]"; 

,这不是一个真正的字符串。这就是你的字节数组的类型和地址。这只不过是一个暂时的参考代码,如果原始数组是GC'd,你甚至不会希望通过真正有趣的本地方法来回忆它。

1

我怀疑你正在尝试做错的事情,这根本不会帮助你,因为尽管你希望内容是相同的,而不是toString()方法的结果。

你不应该使用文本字符串二进制数据,但你可以使用ISO-8859-1

byte[] bytes = random bytes 
String text = new String(bytes, "ISO-8859-1"); 
byte[] bytes2 = text.getBytes("ISO-8859-1"); // gets back the same bytes. 

但是,为了回答你的问题,你可以做到这一点。

Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); 
theUnsafe.setAccessible(true); 
Unsafe unsafe = (Unsafe) theUnsafe.get(null); 
byte[] bytes = new byte[0]; 
unsafe.putInt(bytes, 1L, 0x64964f8e); 
System.out.println(bytes); 

打印

[[email protected] 
0

简单的回答是:c对象的

System.out.println(c)打印基准的表示。 不是 c的内容。 (只有在情况下,对象的toString()未重写此方法)

String b = "[[email protected]"; 
    byte[] c = b.getBytes(); 

    System.out.println(c);    //prints reference's representation of c 
    System.out.println(new String(c)); //prints [[email protected] 
0

"[[email protected]"不是你byte[]的字符串编码。这是默认toString()实现的结果,该实现告诉您类型和参考位置。也许你想使用base64编码,例如使用javax.xml.bind.DatatypeConverter'sparseBase64Binary()printBase64Binary()

byte[] myByteArray = // something 
String myString = javax.xml.bind.DatatypeConverter.printBase64Binary(myByteArray); 
byte[] decoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(myString); 
// myByteArray and decoded have the same contents!