很簡單,程序如下:
class Test{
public static void main(String[] args) throws Exception{
// 漢字變成UFT8編碼
System.out.println(URLEncoder.encode("何楊", "utf-8"));
// 將UFT8編碼的文字還原成漢字
System.out.println(URLDecoder.decode("%E4%BD%95%E6%9D%A8", "utf-8"));
}
}
輸出如下:
%E4%BD%95%E6%9D%A8
何楊
下面是一個輔助的工具類:
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* UTF8轉碼器
* @author heyang
*
*/
public class UTF8Coder{
private static final String UTF_8 = "utf-8";// 編碼形式
/**
* 對文字進行UTF8轉碼
* @param str
* @return
*/
public static String encode(String str){
try {
return URLEncoder.encode(str, UTF_8);
} catch (UnsupportedEncodingException e) {
return null;
}
}
/**
* 將轉碼后的文字還原
* @param str
* @return
*/
public static String decode(String str){
try {
return URLDecoder.decode(str, UTF_8);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}