1. 程式人生 > >unicode碼、字串、utf8碼之間的轉換工具類

unicode碼、字串、utf8碼之間的轉換工具類

package com.anjz.test;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class EncodeUtil {

	/**
	 * 獲取字串的unicode編碼
	 * 
	 * \ufeff控制字元 用來表示「位元組次序標記(Byte Order Mark)」不佔用寬度 unicode碼中一個字元佔用2個位元組
	 * @param s
	 * @return
	 */
	public static String stringToUnicode(String s) {
		if (StringUtils.isEmpty(s)) {
			return null;
		}

		try {
			StringBuffer out = new StringBuffer("");
			byte[] bytes = s.getBytes("unicode");

			for (int i = 0; i < bytes.length - 1; i += 2) {
				out.append("\\u");

				// 將位元組碼轉化成十六進位制(& oxff 是進行補碼操作)
				String str = Integer.toHexString(bytes[i] & 0xff);
				for (int j = str.length(); j < 2; j++) {
					out.append("0");
				}
				out.append(str);
				String str1 = Integer.toHexString(bytes[i + 1] & 0xff);
				for (int j = str1.length(); j < 2; j++) {
					out.append("0");
				}
				out.append(str1);
			}

			out.delete(0, "\\ufeff".length());
			return out.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * unicode碼轉化成字串
	 * @param str
	 * @return
	 */
	public static String unicodeToString(String str) {
		Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
		Matcher matcher = pattern.matcher(str);
		char ch;
		while (matcher.find()) {
			String group = matcher.group(2);
			ch = (char) Integer.parseInt(group, 16);
			String group1 = matcher.group(1);
			str = str.replace(group1, ch + "");
		}
		return str;
	}

	/**
	 * 字串轉化成對應的utf8編碼
	 * @param s
	 * @return 16進位制的資料流
	 */
	public static String convertStringToUTF8(String s) {
		if (s == null || s.equals("")) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		try {
			char c;
			for (int i = 0; i < s.length(); i++) {
				c = s.charAt(i);
				if (c >= 0 && c <= 255) {
					sb.append(Integer.toHexString(c).toUpperCase());
				} else {
					byte[] b;
					b = Character.toString(c).getBytes("utf-8");
					for (int j = 0; j < b.length; j++) {
						int k = b[j];
						// 轉換為unsigned integer 無符號integer
						/*
						 * if (k < 0) k += 256;
						 */
						k = k < 0 ? k + 256 : k;
						// 返回整數引數的字串表示形式 作為十六進位制(base16)中的無符號整數
						// 該值以十六進位制(base16)轉換為ASCII數字的字串
						sb.append(Integer.toHexString(k).toUpperCase());

						// url轉置形式
						// sb.append("%" +Integer.toHexString(k).toUpperCase());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	/**
	 * UTF-8編碼 轉換為對應的 字串
	 * 實現方式:將16進位制數轉化成有符號的十進位制數
	 * @param s
	 * @return
	 */
	public static String convertUTF8ToString(String s) {  
	    if (s == null || s.equals("")) {  
	        return null;  
	    }  
	    try {  
	        s = s.toUpperCase();  
	        int total = s.length() / 2;  
	        //標識位元組長度  
	        int pos = 0;  
	        byte[] buffer = new byte[total];  
	        for (int i = 0; i < total; i++) {  
	            int start = i * 2;  
	            //將字串引數解析為第二個引數指定的基數中的有符號整數。  
	            buffer[i] = (byte) Integer.parseInt(s.substring(start, start + 2), 16);  
	            pos++;  
	        }  
	        //通過使用指定的字符集解碼指定的位元組子陣列來構造一個新的字串。  
	        //新字串的長度是字符集的函式,因此可能不等於子陣列的長度。  
	        return new String(buffer, 0, pos, "UTF-8");  
	    } catch (UnsupportedEncodingException e) {  
	        e.printStackTrace();  
	    }  
	    return s;  
	}  
	
	/**
	 * unicode碼轉化成utf8碼
	 * unicode碼 -> 字串 -> utf8碼
	 * @param str
	 * @return
	 */
	public static String unicodeToUTF8(String str){
		return EncodeUtil.convertStringToUTF8(EncodeUtil.unicodeToString(str));  
	}
	
	/**
	 * utf8碼轉化成unicode碼
	 * utf8碼 -> 字串 -> unicode碼
	 * @param str
	 * @return
	 */
	public static String utf8ToUnicode(String str){
		return EncodeUtil.stringToUnicode(EncodeUtil.convertUTF8ToString(str));  
	}

}

測試程式碼

package com.anjz.test;

import java.io.UnsupportedEncodingException;

public class CodingTest3 {
	public static void main(String[] args) throws UnsupportedEncodingException {
		System.out.println(EncodeUtil.stringToUnicode("木999,你好,不錯,[email protected]#$"));
		System.out.println(EncodeUtil.unicodeToString("\\u6728\\u0039\\u0039\\u0039\\uff0c\\u4f60\\u597d\\uff0c\\u4e0d\\u9519\\u002c\\u007e\\u0021\\u0040\\u0023\\u0024"));
		
		System.out.println(EncodeUtil.convertStringToUTF8("你好"));
		System.out.println(EncodeUtil.convertUTF8ToString("E4BDA0E5A5BD"));
		
		System.out.println(EncodeUtil.unicodeToUTF8("\\u6728\\u0039\\u0039\\u0039\\uff0c\\u4f60\\u597d\\uff0c\\u4e0d\\u9519\\u002c\\u007e\\u0021\\u0040\\u0023\\u0024"));
		
		System.out.println(EncodeUtil.utf8ToUnicode("E69CA8393939EFBC8CE4BDA0E5A5BDEFBC8CE4B88DE994992C7E21402324"));
	}
}
測試結果

\u6728\u0039\u0039\u0039\uff0c\u4f60\u597d\uff0c\u4e0d\u9519\u002c\u007e\u0021\u0040\u0023\u0024
木999,你好,不錯,[email protected]#$
E4BDA0E5A5BD
你好
E69CA8393939EFBC8CE4BDA0E5A5BDEFBC8CE4B88DE994992C7E21402324
\u6728\u0039\u0039\u0039\uff0c\u4f60\u597d\uff0c\u4e0d\u9519\u002c\u007e\u0021\u0040\u0023\u0024