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

前端 未结 13 2165
终归单人心
终归单人心 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:38

    Here's a solution that avoids performing the Charset lookup for every conversion:

    import java.nio.charset.Charset;
    
    private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
    
    String decodeUTF8(byte[] bytes) {
        return new String(bytes, UTF8_CHARSET);
    }
    
    byte[] encodeUTF8(String string) {
        return string.getBytes(UTF8_CHARSET);
    }
    

提交回复
热议问题