1. 程式人生 > >Java unicode中文編碼轉換和反轉

Java unicode中文編碼轉換和反轉

在java的很多配置檔案中,尤其是國際化資源中經常遇到類似\uf432這樣的unicode編碼,蒐集了下該編碼相關的資料,大致處理方法有如下:

1、Unicode轉 漢字字串。

這個過程最簡單的方式就是直接獲取。比如

String cnStr = "\ufeff\u4e2d\u56fd\u4eba";

System.out.println(cnStr); 即可獲取對應的漢字字元  “中國人”;

但是呢,每次從輸出讀的話也未免過於不方便了,我們使用方法來做轉換,直接獲取。

參考如下

	public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");    
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");    
        }
        return str;
    }

2、獲取字串的unicode編碼,這個我們可以通過直接獲取字串的unicode二進位制,然後將其byte轉換成對應的16進製表示即可,函式示例如下

static String getUnicode(String s) {
		try {
			StringBuffer out = new StringBuffer("");
			byte[] bytes = s.getBytes("unicode");
			for (int i = 0; i < bytes.length - 1; i += 2) {
				out.append("\\u");
				String str = Integer.toHexString(bytes[i + 1] & 0xff);
				for (int j = str.length(); j < 2; j++) {
					out.append("0");
				}
				String str1 = Integer.toHexString(bytes[i] & 0xff);
				out.append(str1);
				out.append(str);
				
			}
			return out.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

通過上面的方式便可完整的使用unicode編碼了,大家有其他方式的轉換也可以告訴我下,互相學習