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

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

    As an alternative, StringUtils from Apache Commons can be used.

     byte[] bytes = {(byte) 1};
     String convertedString = StringUtils.newStringUtf8(bytes);
    

    or

     String myString = "example";
     byte[] convertedBytes = StringUtils.getBytesUtf8(myString);
    

    If you have non-standard charset, you can use getBytesUnchecked() or newString() accordingly.

提交回复
热议问题