汉字UTF8编码转换

import java.io.UnsupportedEncodingException;

public class HanUtf8 {
    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            System.out.println("Input with format:\ncommand \\xAE\\xEC\\x9c... or command 汉字。。。");
            return;
        }
        if (args[0].contains("x")) {
            System.out.println(code2han(args[0]));
        } else {
            System.out.println(han2code(args[0]));
        }
    }

    public static String code2han(String code) {
//      String[] codeArr = code.split("x");
        String[] codeArr = code.split("\\\\x");    //str.split("\\\\")表示用\分割字符串。
        byte[] bArr = new byte[codeArr.length-1];
        for(int i=1; i<codeArr.length; i++){
            int n = Integer.parseInt(codeArr[i], 16);
            byte b = new Integer(n).byteValue();
            bArr[i-1] = b;
        }
        try {
            return new String(bArr, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String han2code(String str) {
        byte[] bArr = str.getBytes();
        String rtn = "";
        for (byte b : bArr) {
            rtn += "\\x" + Integer.toHexString(b & 0xFF);
        }
        return rtn;
    }

}
posted @ 2018-12-08 20:12  xuejianbest  阅读(809)  评论(0编辑  收藏  举报