如何将String转换为字节数组?

我有一个String,它包含字节数组的String值。 我怎么能把这个字符串转换为字节数组? 我怎么试过:

String stringValue="33321232"; //the bytes in String byte[] bytes= (byte[])stringValue; System.out.println(getByteArrayAsString(bytes)); 

getByteArrayAsString方法应该返回结果String: 33321232 ,所以与stringValue相同。 (这是我的方法,它是有效的,但如何获取bytes ?)

谢谢!

我有一个String,它包含字节数组的String值。

这一点尚不清楚。 如果您已将二进制数据转换为文本,那么您是如何做到的? 这应该指导你如何转换回来。 例如,如果您已经开始使用任意二进制数据(例如某种forms的图像),那么通常您希望使用base64或hex转换为字符串。 如果您从文本数据开始,那就是另一回事了。

字符串不是字节数组,这就是转换失败的原因。 对于基本上是文本的数据,需要在二进制和文本之间进行转换,应用编码 (在Java中也称为charset有点令人困惑)。

其他答案建议使用new String(byte[])String.getBytes() 。 我强烈建议不要使用这些成员 – 使用指定编码的成员:

 new String(byte[], String) // the string argument is the charset new String(byte[], Charset) String.getBytes(String) // the string argument is the charset String.getBytes(Charset) 

如果您没有指定编码,它将使用平台默认编码,这通常不是您想要的。 您需要考虑要使用的编码。

使用Charset指定编码比使用字符串更简洁 – 如果您使用Java 7,则值得了解StandardCharsets ,例如

 byte[] bytes = stringValue.getBytes(StandardCharsets.UTF_8); System.out.println(new String(bytes, StandardCharsets.UTF_8); 

尝试像这样调用getBytes()

 String stringValue="33321232"; //the bytes in String bytes[] b=stringValue.getBytes(); 

有关更多信息,请查看oracle docs

试试这个

  String result = new String(bytes); System.out.println(result);