首頁  >  文章  >  電腦教學  >  如何在Java中將字串轉換為GB2312編碼?

如何在Java中將字串轉換為GB2312編碼?

王林
王林轉載
2024-01-20 08:42:13495瀏覽

如何在Java中將字串轉換為GB2312編碼?

Java怎麼將字串轉換為GB2312原始編碼

@Test

public void test333(){

String a="青白";

try {

byte[] b=a.getBytes("GB2312");

System.out.println(bytesToHexFun1(b));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

}

//將byte數組轉成16進位字串

public static String bytesToHexFun1(byte[] bytes) {

char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',

'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

// 一個byte為8位,可用兩個十六進位位標識

char[] buf = new char[bytes.length * 2];

int a = 0;

int index = 0;

for(byte b : bytes) { // 使用除與取餘進行轉換

if(b

a = 256 b;

} else {

a = b;

}

buf[index ] = HEX_CHAR[a / 16];

buf[index ] = HEX_CHAR[a % 16];

}

return new String(buf);

}

中心思想就是先轉成GB2312的byte數組,再轉成16進位就可以了。

java String Byte轉換的問題

1、在網頁中輸出中文。

JAVA在網路傳輸中使用的編碼是"ISO-8859-1",故在輸出時需要進行轉化,如:

String str="中文";

str=new String(str.getBytes("GB2312"),"8859_1");

但假如在編譯程序時,使用的編碼是“GB2312”,並且在中文平台上運行此程序,不會出現此問題,一定要注重。

2、從參數讀取中文

這正好與在網頁中輸出相反如:

str=new String(str.getBytes("8859_1"),"GB2312");

3、操作DB中的中文問題

一個較簡單的方法是:在「控制面扳」中,把「區域」設定為「英語(美國)」。假如還會出現亂碼,還可進行如下設定:

取中文時:str=new String(str.getBytes("GB2312"));

向DB中輸入中文:str=new String(str.getBytes("ISO-8859-1"));

4、在jsp中的中文解決:

在「控制面扳」中,把「區域」設定為「英文(美國)」.

在JSP頁面中加入:

假如還不行正常顯示,則還要進行下面的轉換:

如:name=new String(name.getBytes("ISO-8859-1"),"GBK");

就不會出現中文問題了。

java String類型轉換

網路上找了一個,你試試看:

/**

* unicode轉字串

* @param str

* @return

*/

public static String unicode2Str(String str) {

StringBuffer sb = new StringBuffer();

String[] arr = str.split("\\\\u");

int len = arr.length;

sb.append(arr[0]);

for(int i=1; i

String tmp = arr[i];

char c = (char)Integer.parseInt(tmp.substring(0, 4), 16);

sb.append(c);

sb.append(tmp.substring(4));

}

return sb.toString();

}

/**

* 字串轉unicode

* @param str

* @return

*/

public static String str2Unicode(String str) {

StringBuffer sb = new StringBuffer();

char[] charArr = str.toCharArray();

for (char ch : charArr) {

if (ch > 128) {

sb.append("\\u" Integer.toHexString(ch));

} else {

sb.append(ch);

}

}

return sb.toString();

}

public static void main(String[] args) {

System.out.println(str2Unicode("222ds測1試aa"));

String str = "\u6d4b1\u8bd5aa";

System.out.println(unicode2Str(str));

}

以上是如何在Java中將字串轉換為GB2312編碼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:docexcel.net。如有侵權,請聯絡admin@php.cn刪除