EN
Java - convert String to UTF-8 bytes
9
points
In this short article we would like to show how to convert String
to UTF-8 bytes in Java.
Quick solution:
// import java.nio.charset.StandardCharsets;
String text = "Hi, there!";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Practical examples
1. Conversion with predefined property
Java 1.7 introduced StandardCharsets
class with predefined properties.
package example;
import java.nio.charset.StandardCharsets;
public class Program {
public static void main(String[] args) {
String text = "Hi, there!";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
printBytes(bytes); // 72 105 44 32 116 104 101 114 101 33
}
private static void printBytes(byte[] data) {
for (int i = 0; i < data.length; ++i) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(data[i]);
}
}
}
2. Conversion with charset name
Using charset name we are able to make String
conversion too.
package example;
import java.io.UnsupportedEncodingException;
public class Program {
public static void main(String[] args) throws UnsupportedEncodingException {
String text = "Hi, there!";
byte[] bytes = text.getBytes("utf8");
printBytes(bytes); // 72 105 44 32 116 104 101 114 101 33
}
private static void printBytes(byte[] data) {
for (int i = 0; i < data.length; ++i) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(data[i]);
}
}
}