问题
I have a String, which contains the byte array's String value. How could I convert this String to byte array? How I tried:
String stringValue="33321232"; //the bytes in String
byte[] bytes= (byte[])stringValue;
System.out.println(getByteArrayAsString(bytes));
The getByteArrayAsString
method should give back the result String: 33321232
, so the same which is the stringValue
. (This is my method, it is works, but how to get the bytes
?)
Thank you!
回答1:
I have a String, which contains the byte array's String value.
This is unclear to start with. If you've converted binary data to text, how have you done that? That should guide you as to how you convert back. For example, if you've started with arbitrary binary data (e.g. an image in some form) then typically you'd want to convert to a string using base64 or hex. If you started with text data, that's a different matter.
A string isn't a byte array, which is why the cast fails. For data which is fundamentally text, need to convert between binary and text, applying an encoding (also known somewhat confusingly as a charset in Java).
Other answers have suggested using new String(byte[])
and String.getBytes()
. I would strongly recommend against using those members - use the ones which specify an encoding instead:
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)
If you don't specify an encoding, it will use the platform default encoding, which is often not what you want. You need to consider which encoding you want to use.
Using a Charset
to specify the encoding is cleaner than just using the string - it's worth being aware of StandardCharsets if you're using Java 7, e.g.
byte[] bytes = stringValue.getBytes(StandardCharsets.UTF_8);
System.out.println(new String(bytes, StandardCharsets.UTF_8);
回答2:
try calling getBytes() like this way
String stringValue="33321232"; //the bytes in String
bytes[] b=stringValue.getBytes();
For more info check oracle docs
回答3:
Try this
String result = new String(bytes);
System.out.println(result);
来源:https://stackoverflow.com/questions/19834854/how-to-cast-string-to-byte-array