Converting Strings and Byte Arrays in UTF-8 Using Java
In Java, working with both Strings and byte arrays is common. Encoding and decoding between these two formats is necessary for various operations. This question addresses how to perform these conversions specifically using the UTF-8 encoding.
Converting String to Byte Array (UTF-8)
To convert a String into a UTF-8 encoded byte array, use the getBytes() method along with the StandardCharsets.UTF_8 constant:
String s = "some text here"; byte[] b = s.getBytes(StandardCharsets.UTF_8);
Converting Byte Array to String (UTF-8)
To convert a UTF-8 encoded byte array into a String, use the new String() constructor along with the StandardCharsets.UTF_8 constant:
byte[] b = {(byte) 99, (byte)97, (byte)116}; String s = new String(b, StandardCharsets.UTF_8);
Remember to use the appropriate encoding name (e.g., "US-ASCII" or "UTF-8") based on the actual encoding of the byte array.
The above is the detailed content of How to Convert Strings and Byte Arrays Using UTF-8 in Java?. For more information, please follow other related articles on the PHP Chinese website!