从ORACLE存储过程得到字符串全是"?"的乱码,数字能正常显示,我把这段代码转换成unicode使用如下方法:        测试用:getUnicode("2008-02-28{北京{天津{上海"); public static String toHEXString(byte b) { 
return (""+"0123456789abcdef".charAt(0xf&b>>4)+"0123456789abcdef".charAt(b&0xF)); 
}  public static String getUnicode(String setStr) { 
String szRet = ""; 
String szRetTmp = null; 
String str = null; 
try { 
try { 
str = new String(setStr.getBytes("gb2312"),"gb2312"); 
}
catch(Exception ex){ 
ex.printStackTrace(); 

byte[] bb = str.getBytes("UTF16"); 
for(int i = 2; i < bb.length; i++) 

i++; 
if(bb[i-1] != 0) 
szRetTmp = "\\u" + toHEXString(bb[i-1]) + toHEXString(bb[i]); 
else 
szRetTmp = new String(bb,i,1,"gb2312"); 
szRet = szRet + szRetTmp; 

}catch(Exception ex) { 
szRet="Sorry Convert2Unicode method fail!"; 
ex.printStackTrace(); 

return szRet; 
}        得到unicode:2008-02-28{\u5317\u4eac{\u5929\u6d25{\u4e0a\u6d77,然后把这段代码再转换为字符格式,如下方法:        unicodeToStr(getUnicode("2008-02-28{北京{天津{上海"));
        或
         String unicodestr=getUnicode("2008-02-28{北京{天津{上海");
        unicodeToStr(unicodestr); public String unicodeToStr(String uStr){
  String str = uStr;
  System.out.println("str:"+str+" "+str.length());
  String[] unicode = str.split("\\\\u");
  StringBuffer buf = new StringBuffer(unicode.length - 1);   
  for(int i = 1; i < unicode.length; i++)
  {
      buf.append(Integer.parseInt(unicode[i],16));
  }
  System.out.println(buf.toString());
return str;
}        总是提示错误:
        java.lang.NumberFormatException: For input string: "4eac{"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)        而如果直接使用unicodeToStr("2008-02-28{\u5317\u4eac{\u5929\u6d25{\u4e0a\u6d77");就不会报错,请问该怎么改呀,或者使用其它方法把unicode 转化为字符格式?
        谢谢了!

解决方案 »

  1.   

    手头正好有份和楼主需求一样的资料,楼主可以参考下: public static String gbk2Unicode(String str) {
    StringBuffer ret = new StringBuffer();
    String tmp = null;
    try {
    byte[] bb = str.getBytes("UTF-16");
    for (int i = 3; i < bb.length; i += 2) {
    if (bb[i - 1] != 0)
    tmp = toHEXString(bb[i - 1]) + toHEXString(bb[i]);
    else
    tmp = "00" + toHEXString(bb[i]);
    ret.append("\\u").append(tmp);
    }
    return ret.toString();
    } catch (Exception e) {
    return str;
    }
    } public static String unicode2GBK(String str) {
    String[] s = str.split("\\\\u");
    StringBuffer ret = new StringBuffer();
    for (int i = 1; i < s.length; i++) {
    ret.append((char) Integer.parseInt(s[i], 16));
    }
    return ret.toString();
    } private static String toHEXString(byte b) {
    return ("" + "0123456789ABCDEF".charAt(0xf & b >> 4) + "0123456789ABCDEF"
    .charAt(b & 0xF));
    }
      

  2.   


    String temp = gbk2Unicode("2008-02-28{北京{天津{上海");
    System.out.println("gbk2Unicode:" + temp);
    System.out.println("unicode2GBK:" + unicode2GBK(temp));验证可以通过