unicode转化汉字 汉字转化unicode编码


import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Translator {
    /**
     * 汉字转Unicode
     *
     * @param s
     * @return
     */
    public static String c2u(String s) {
        String ret = "";
        String[] as = new String[s.length()];
        for (int i = 0; i < s.length(); i++) {
            as[i] = Integer.toHexString(s.charAt(i) & 0xffff);
            ret = ret + "\\u" + as[i];
        }
        return ret;
    }
    /**
     * Unicode转汉字
     *
     * @param s
     * @return
     */
    public static String u2c(String s) {
        String ret = "";
        Pattern p = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = p.matcher(s);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            ret = s.replace(matcher.group(1), ch + "");
            s = ret;
        }
        return ret;
    }
    public void work(String mode, String content) {
        if (mode.equals("U2C")) {
            System.out.println(u2c(content));
        } else if (mode.equals("C2U")) {
            System.out.println(c2u(content));
        } else {
            System.err.println("Error Mode, [MODE: U2c/C2U]");
        }
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("Usage:\n\t[MODE(U2C/C2U)] <content>");
            System.exit(1);
        }
        String mode = args[0].trim().toUpperCase();
        String content = args[1].trim();
        new Translator().work(mode, content);
    }
}