java String 转utf-8编码
/**
* Get XML String of utf-8
*
* @return XML-Formed string
*/
public static String getUTF8XMLString(String xml) {
// A StringBuffer Object
StringBuffer sb = new StringBuffer();
sb.append(xml);
String xmString = "";
String xmlUTF8="";
try {
xmString = new String(sb.toString().getBytes("UTF-8"));
xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");
System.out.println("utf-8 编码:" + xmlUTF8) ;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return to String Formed
return xmlUTF8;
}
utf-8转Java String
/**
* @param fromStr : 要转换的原始字符串
* @return : 得到转换后的字符串
*/
private String is(String fromStr) {
StringBuffer stringBufferResult = new StringBuffer();
for (int i = 0; i < fromStr.length(); i++) {
char chr = fromStr.charAt(i);
if (chr == '%') {
StringBuffer stringTmp = new StringBuffer();
stringTmp.append(fromStr.charAt(i + 1)).append(fromStr.charAt(i + 2));
//转换字符,16进制转换成整型
stringBufferResult.append((char) (Integer.valueOf(stringTmp.toString(), 16).intValue()));
i = i + 2;
continue;
}
stringBufferResult.append(chr);
}
String newStr = null; //编码转换
try {
newStr = new String(stringBufferResult.toString().getBytes("Cp1252"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return newStr;
}