java特殊字符转Unicode问题

[code="java"]
有谁知道java中的特殊字符 如"#,&,#"等特殊符号如何转成unicode编码

哎,搞了我两天了,头都大了 ,网上有些案例只是针对汉字的,而遇到这些特殊字符时则不进行处理了。。]。。。[/code]

还是考虑自己写函数来实现吧,参考代码
[code="java"]
//转换为unicode
public static void encodeUnicode(final String gbString) {

char[] utfBytes = gbString.toCharArray();

String unicodeBytes = "";

for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {

String hexB = Integer.toHexString(utfBytes[byteIndex]);

if (hexB.length() <= 2) {

hexB = "00" + hexB;

}

unicodeBytes = unicodeBytes + "\u" + hexB;

}

System.out.println(unicodeBytes);

}

[/code]

encodeURI 方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。

该方法的目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#

encodeURIComponent()对url中的特殊字符做出来,将他们转化成对应的ASCII码

6.这些方法都是JavaScript 函数,也就是只能够在JavaScript中使用。

返回统一资源标识符 (URI) 的一个已编码组件的非编码形式。

  decodeURIComponent(encodedURIString)

  必选的 encodedURIString 参数代表一个已编码的 URI 组件。

说明
  URIComponent 是一个完整的 URI 的一部分。

  假如 encodedURIString 无效,将产生一个 URIError。

没有直接的方式,你必须分2步来做,第一步转成unicode格式,第二步加上\u

[code="java"]
//unicode转化汉字

public static StringBuffer decodeUnicode(final String dataStr) {

final StringBuffer buffer = new StringBuffer();

String tempStr = "";

String operStr = dataStr;

if (operStr != null && operStr.indexOf("\u") == -1)

return buffer.append(operStr);

if (operStr != null && !operStr.equals("")

&& !operStr.startsWith("\u")) {

tempStr = operStr.substring(0, operStr.indexOf("\u"));

operStr = operStr.substring(operStr.indexOf("\u"), operStr.length());// operStr字符一定是以unicode编码字符打头的字符串

}

buffer.append(tempStr);

// 循环处理,处理对象一定是以unicode编码字符打头的字符串

while (operStr != null && !operStr.equals("")&& operStr.startsWith("\u")) {

tempStr = operStr.substring(0, 6);

operStr = operStr.substring(6, operStr.length());

String charStr = "";

charStr = tempStr.substring(2, tempStr.length());

char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。

buffer.append(new Character(letter).toString());

if (operStr.indexOf("\u") == -1) {

buffer.append(operStr);

} else { // 处理operStr使其打头字符为unicode字符

tempStr = operStr.substring(0, operStr.indexOf("\u"));

operStr = operStr.substring(operStr.indexOf("\u"), operStr.length());

buffer.append(tempStr);

}

}

return buffer;

}

[/code]

源自网络