Languages
[Edit]
EN

Java - convert String to UTF-8 bytes

9 points
Created by:
AnnLen
9880

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]);
        }
    }
}
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join