Home >Java >javaTutorial >How to Convert Strings and Byte Arrays Using UTF-8 in Java?

How to Convert Strings and Byte Arrays Using UTF-8 in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 21:34:11309browse

How to Convert Strings and Byte Arrays Using UTF-8 in Java?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn