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:
xxxxxxxxxx
1
// import java.nio.charset.StandardCharsets;
2
3
String text = "Hi, there!";
4
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Java 1.7 introduced StandardCharsets
class with predefined properties.
xxxxxxxxxx
1
package example;
2
3
import java.nio.charset.StandardCharsets;
4
5
public class Program {
6
7
public static void main(String[] args) {
8
9
String text = "Hi, there!";
10
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
11
12
printBytes(bytes); // 72 105 44 32 116 104 101 114 101 33
13
}
14
15
private static void printBytes(byte[] data) {
16
for (int i = 0; i < data.length; ++i) {
17
if (i > 0) {
18
System.out.print(" ");
19
}
20
System.out.print(data[i]);
21
}
22
}
23
}
Using charset name we are able to make String
conversion too.
xxxxxxxxxx
1
package example;
2
3
import java.io.UnsupportedEncodingException;
4
5
public class Program {
6
7
public static void main(String[] args) throws UnsupportedEncodingException {
8
9
String text = "Hi, there!";
10
byte[] bytes = text.getBytes("utf8");
11
12
printBytes(bytes); // 72 105 44 32 116 104 101 114 101 33
13
}
14
15
private static void printBytes(byte[] data) {
16
for (int i = 0; i < data.length; ++i) {
17
if (i > 0) {
18
System.out.print(" ");
19
}
20
System.out.print(data[i]);
21
}
22
}
23
}