Java UnicodeHelper | 影の域

影の域

关注web前端,追逐html5脚步,体会code人生

Java UnicodeHelper

| 3,681 点击

public class UnicodeHelper {

 public static String encode(String gbString) {
  if (gbString == null || gbString.length() == 0)
   return "";
  char c = '\0';
  int k = gbString.length();
  StringBuffer stringbuffer = new StringBuffer(k);
  for (int j = 0; j < k; j++) {
   int i = c;
   c = gbString.charAt(j);
   switch (c) {
   case 34: // '"'
   case 92: // '\\'
    stringbuffer.append('\\');
    stringbuffer.append(c);
    break;

   case 47: // '/'
    if (i == 60)
     stringbuffer.append('\\');
    stringbuffer.append(c);
    break;

   case 8: // '\b'
    stringbuffer.append("\\b");
    break;

   case 9: // '\t'
    stringbuffer.append("\\t");
    break;

   case 10: // '\n'
    stringbuffer.append("\\n");
    break;

   case 12: // '\f'
    stringbuffer.append("\\f");
    break;

   case 13: // '\r'
    stringbuffer.append("\\r");
    break;

   default:
    if (c >= '0' && c <= '9' || c >= 'A' && c <= 'z') {
     stringbuffer.append(c);
    } else {
     String s1 = (new StringBuilder()).append("000″).append(Integer.toHexString(c)).toString();
     stringbuffer.append("\\u").append(s1.substring(s1.length() – 4));
    }
    break;
   }
  }

  return stringbuffer.toString();
 }

 private static String decode(final String unicodeStr) {
  int start = 0, end = 0;
  final StringBuffer buffer = new StringBuffer();
  String charStr = "";
  while (start > -1) {

   end = unicodeStr.indexOf("\\u", start + 2);

   if (end == -1) {
    if (unicodeStr.length() >= start + 6) {
     charStr = unicodeStr.substring(start + 2, start + 6);
     char letter = (char) Integer.parseInt(charStr, 16);
     buffer.append(new Character(letter));
     buffer.append(unicodeStr.substring(start + 6, unicodeStr.length()));
    } else {
     buffer.append(unicodeStr.substring(start, unicodeStr.length()));
    }
   } else {
    charStr = unicodeStr.substring(start + 2, start + 6);
    char letter = (char) Integer.parseInt(charStr, 16);
    buffer.append(new Character(letter));

    if (end – start > 6) {
     buffer.append(unicodeStr.substring(start + 6, end));
    }
   }

   start = end;
  }
  return buffer.toString();
 }

 public static void main(String[] args) {
  String str = "影之abcdefghijklmnopqrstuvwxyz0123456789,.!{|}/_-迷惑";
  String json = UnicodeHelper.encode(str);

  System.out.println(json);
  System.out.println(UnicodeHelper.decode(json));

  String ss = "爱仕达飒飒sd@#4**:{'sss大发";
  String json2 = UnicodeHelper.encode(ss);
  System.out.println(json2);
  System.out.println(UnicodeHelper.decode(json2));
 }

}