How to convert String to byte without changing?

前端 未结 4 830
鱼传尺愫
鱼传尺愫 2021-01-29 07:28

I need a solution to convert String to byte array without changing like this:

Input:

 String s=\"Test\";

Output:

String         


        
相关标签:
4条回答
  • 2021-01-29 08:05

    You may try the following code snippet -

    String string = "Sample String";
    
    byte[] byteArray = string.getBytes();
    
    0 讨论(0)
  • 2021-01-29 08:08

    You can revert back using

    String originalString = new String(b, "UTF-8");

    That should get you back your original string. You don't want the bytes printed out directly.

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

    You should always make sure serialization and deserialization are using the same character set, this maps characters to byte sequences and vice versa. By default String.getBytes() and new String(bytes) uses the default character set which could be Locale specific.

    Use the getBytes(Charset) overload

    byte[] bytes = s.getBytes(Charset.forName("UTF-8"));
    

    Use the new String(bytes, Charset) constructor

    String andBackAgain = new String(bytes, Charset.forName("UTF-8"));
    

    Also Java 7 added the java.nio.charset.StandardCharsets class, so you don't need to use dodgy String constants anymore

    byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
    String andBackAgain = new String(bytes, StandardCharsets.UTF_8);
    
    0 讨论(0)
  • 2021-01-29 08:20

    In general that's probably not what you want to do, unless you're serializing or transmitting the data. Also, Java strings are UTF-16 rather than UTF-8, which what more like what you're expecting. If you really do want/need this then this should work:

    String str = "Test";
    byte[] raw = str.getBytes(new Charset("UTF-8", null));
    
    0 讨论(0)
提交回复
热议问题