天天看點

UnicodeUtil Unicode工具

package kyle.leis.eo.billing.receivable.test;

import java.io.UnsupportedEncodingException;

public class UnicodeUtil {

	public static void main(String[] args) throws UnsupportedEncodingException {
		String str = "簡介ABC";
		String strEncode = encode(str);
		System.out.println(str + " --的unicode編碼是:" + strEncode);
		System.out.println(strEncode + " --解碼為:" + decode(strEncode));
	}

	/**
	 * 編碼
	 * @param str
	 * @return
	 */
	public static String encode(String str) {
		if(str == null || str.isEmpty()) {
			return null;
		}
		char[] utfBytes = str.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;
	}

	/**
	 * 解碼
	 * @param str
	 * @return
	 */
	public static String decode(String str) {
		if(str == null || str.isEmpty()) {
			return null;
		}
		int start = 0;
		int end = 0;
		final StringBuffer buffer = new StringBuffer();
		while (start > -1) {
			end = str.indexOf("\\u", start + 2);
			String charStr = "";
			if (end == -1) {
				charStr = str.substring(start + 2, str.length());
			} else {
				charStr = str.substring(start + 2, end);
			}
			char letter = (char) Integer.parseInt(charStr, 16);
			buffer.append(new Character(letter).toString());
			start = end;
		}
		return buffer.toString();
	}
}