JAVA中GBK格式String与Byte数组互转

//byte数组转String

public static byte[] string_to_gbk_bytes(String data) {
  int i = 0;
  byte[] s = null;

  try {
    s = data.getBytes("GBK");
    i = s.length;
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
  }

  byte[] temp = new byte[i + 1];
  System.arraycopy(s, 0, temp, 0, i);
  temp[i] = 0;

  return temp;
}//String转byte数组
public static String gbk_bytes_to_string(byte[] data) {
    int i;
    String s = "";

    for (i = 0; i < data.length; ++i) {
      if (data[i] == 0) {
        break;
      }
    }

    byte[] temp = new byte[i];
    System.arraycopy(data, 0, temp, 0, temp.length);

    try {
      s = new String(temp, "GBK");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    return s;
  }

你可能感兴趣的:(工具方法,GBK,String转byte数组,byte数组转String)