Java String change encoding

Description

Java String change encoding

import java.io.UnsupportedEncodingException;

public class Main {
  public static void main(String[] argv) throws Exception {
    String s = "demo2s.com";
    String fencode = "UTF-8";
    String bencode = "UTF-16";
    System.out.println(changCoding(s, fencode, bencode));
  }//w  ww.  ja v  a2 s . c  o m

  public static String changCoding(String s, String fencode, String bencode) {
    try {
      String str = new String(s.getBytes(fencode), bencode);
      return str;
    } catch (Exception e) {
      return s;
    }
  }
  /**
   * Returns the UTF-8 bytes for the given String, suppressing
   * UnsupportedEncodingException (in lieu of log message)
   * 
   * @param input
   *          The source string
   * @return The UTF-8 encoding for the given string
   */
  public static byte[] getBytes(String input) {
    try {
      return input.getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
      return input.getBytes(); // default encoding
    }
  }
}



PreviousNext

Related