How to convert Strings to and from UTF8 byte arrays in Java

前端 未结 13 2164
终归单人心
终归单人心 2020-11-22 13:05

In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to c

相关标签:
13条回答
  • 2020-11-22 13:42

    Convert from String to byte[]:

    String s = "some text here";
    byte[] b = s.getBytes(StandardCharsets.UTF_8);
    

    Convert from byte[] to String:

    byte[] b = {(byte) 99, (byte)97, (byte)116};
    String s = new String(b, StandardCharsets.US_ASCII);
    

    You should, of course, use the correct encoding name. My examples used US-ASCII and UTF-8, the two most common encodings.

    0 讨论(0)
提交回复
热议问题