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

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

    You can convert directly via the String(byte[], String) constructor and getBytes(String) method. Java exposes available character sets via the Charset class. The JDK documentation lists supported encodings.

    90% of the time, such conversions are performed on streams, so you'd use the Reader/Writer classes. You would not incrementally decode using the String methods on arbitrary byte streams - you would leave yourself open to bugs involving multibyte characters.

提交回复
热议问题