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