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
Release: 2024-11-30 21:34:11
Original
282 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template