Sunday, January 26, 2014

How to convert Strings to and from UTF8 byte arrays?

Source:
public class UTF8Example {
   public static void main(String[] args) {

      String s1 = "This is a string";
      byte[] b = null;
      String s2 = null;

      try {
         //Convert from String to byte[]:
         b = s1.getBytes("UTF-8");

         //Convert from byte[] to String:
         s2 = new String(b, "UTF-8");
      } catch (Exception e) {
      }

      System.out.println(s2);
   }
}

Output:
   $ java UTF8Example 
   This is a string

Blog Archive