java中文和unicode编码相互转换(转)

时间:2021-07-04 20:16:17

 

工具类代码如下:

package aa.com;

import java.io.UnsupportedEncodingException;

public class UnicodeUtil {

    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "简介";
        System.err.println(s+" --的unicode编码是:"+encoding(s));
        System.err.println(encoding(s) + " --转换成中文是:"+decodeUnicode(encoding(s)));
        System.err.println("\\u9EC4%u5927" + " --转换成中文是:"+decodeUnicode("\\u9EC4\\u5927"));
    }
    
    /*
     * 中文转unicode编码
     */
    public static String encoding(String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }
    /*
     * unicode编码转中文
     * 系统中接受中文参数变成百分号,如:“黄大”-->“%u9EC4%u5927”
     * 而实际上内容对应,应该是:“黄大”-->“\u9EC4\u5927”,中文变unicode
     */
    public static String decodeUnicode(String dataStr) {
        dataStr = dataStr.replace("%","\\");//这行酌情不要 int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }
}