Return UTF-8 encoded byte[] representation of a String in Java
Description
The following code shows how to return UTF-8 encoded byte[] representation of a String.
Example
// ww w . j a v a 2s .c o m
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class Main {
public static void main(String[] argv) {
System.out.println(Arrays.toString(getBytesUtf8("java2s.com")));
}
public static final byte[] getBytesUtf8(String string) {
if (string == null) {
return new byte[0];
}
try {
return string.getBytes("UTF-8");
} catch (UnsupportedEncodingException uee) {
return new byte[] {};
}
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »