Is Chinese String in GBK encoding - Android Internationalization

Android examples for Internationalization:Chinese

Description

Is Chinese String in GBK encoding

Demo Code

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class Main {

  public static String getChineseString(String str) {
    String resultStr = str;//from  w ww .ja v  a 2  s  .  c  o m
    String UTF_Str = "";
    String GB_Str = "";
    boolean isISO = false;

    try {

      isISO = isCharset(resultStr, "ISO-8859-1");
      if (isISO) {
        try {

          if (isGBK(resultStr)) {
            GB_Str = new String(resultStr.getBytes("ISO-8859-1"), "GBK");
          } else if (isCharset(resultStr, "UTF-8")) {
            UTF_Str = new String(resultStr.getBytes("ISO-8859-1"), "UTF-8");
          }
        } catch (UnsupportedEncodingException e) {
        }

      }
    } catch (Exception e) {
    }

    return resultStr;
  }

  public static boolean isCharset(String str, String charsetName) {
    return Charset.forName(charsetName).newEncoder().canEncode(str);
  }

  public static boolean isGBK(String str) {
    char[] chars = str.toCharArray();
    boolean isGBK = false;
    for (int i = 0; i < chars.length; i++) {
      byte[] bytes = ("" + chars[i]).getBytes();
      if (bytes.length == 2) {
        int[] ints = new int[2];
        ints[0] = bytes[0] & 0xff;
        ints[1] = bytes[1] & 0xff;
        if (ints[0] >= 0x81 && ints[0] <= 0xFE && ints[1] >= 0x40 && ints[1] <= 0xFE) {
          isGBK = true;
          break;
        }
      }
    }
    return isGBK;
  }
}

Related Tutorials