1. 程式人生 > >java對unicode的編碼 和 解碼

java對unicode的編碼 和 解碼

由於今天再傳輸過程中出現了編碼問題,所以打算對傳輸的url進行url編碼。經過查詢和驗證 整理以下兩種方法

用到的包

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


	/**
	 * unicode編碼
	 * @param String str
	 * @return String
	 */
	public static String encodeUnicode(String string) {
		 
	    StringBuffer unicode = new StringBuffer();
	 
	    for (int i = 0; i < string.length(); i++) {
	 
	        // 取出每一個字元
	        char c = string.charAt(i);
	 
	        // 轉換為unicode
	        unicode.append("\\u00" + Integer.toHexString(c));
	    }
	 
	    return unicode.toString();
	}

	/**
	 * unicode 解碼
	 * @param String str
	 * @return String
	 */
	 public static String decodeUnicode(String str) {
		  Charset set = Charset.forName("UTF-16");
		  Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
		  Matcher m = p.matcher( str );
		  int start = 0 ;
		  int start2 = 0 ;
		  StringBuffer sb = new StringBuffer();
		  while( m.find( start ) ) {
		   start2 = m.start() ;
		   if( start2 > start ){
		    String seg = str.substring(start, start2) ;
		    sb.append( seg );
		   }
		   String code = m.group( 1 );
		   int i = Integer.valueOf( code , 16 );
		   byte[] bb = new byte[ 4 ] ;
		   bb[ 0 ] = (byte) ((i >> 8) & 0xFF );
		   bb[ 1 ] = (byte) ( i & 0xFF ) ;
		   ByteBuffer b = ByteBuffer.wrap(bb);
		   sb.append( String.valueOf( set.decode(b) ).trim() );
		   start = m.end() ;
		  }
		  start2 = str.length() ;
		  if( start2 > start ){
		   String seg = str.substring(start, start2) ;
		   sb.append( seg );
		  }
		  return sb.toString() ;
	}
需要注意的是  如果需要轉碼解碼的字串中含有中文,則這兩種方法是不適用的。