How to convert String to byte without changing?

前端 未结 4 946
鱼传尺愫
鱼传尺愫 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: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);
    

提交回复
热议问题