0

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!

victorio
  • 6,224
  • 24
  • 77
  • 113
  • 2
    `byte[] java.lang.String.getBytes()` (ps: I'm not sure you even searched on the Internet, because it's quite easy to find: google "java string to byte array"). – sp00m Nov 07 '13 at 11:35
  • 1
    Found this on stackoverflow – daark Nov 07 '13 at 11:36
  • 1
    Apart from looking at the answers which tell you how to do it properly, you should learn about casting. Casting cannot help with a problem like this. Use it carefully, and only when the efect is full yunderstood. – Zane Nov 07 '13 at 11:37

3 Answers3

3

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);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

try calling getBytes() like this way

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

For more info check oracle docs

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
-2

Try this

 String result = new String(bytes);
 System.out.println(result);
Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70