How to cast String to byte array?

前端 未结 3 1620
别跟我提以往
别跟我提以往 2021-01-29 09:03

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\"; //th         


        
相关标签:
3条回答
  • 2021-01-29 09:38

    try calling getBytes() like this way

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

    For more info check oracle docs

    0 讨论(0)
  • 2021-01-29 09:58

    Try this

     String result = new String(bytes);
     System.out.println(result);
    
    0 讨论(0)
  • 2021-01-29 10:01

    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);
    
    0 讨论(0)
提交回复
热议问题