Ejbにおける文字符号化変換の問題
2490 ワード
私たちがEjbを使っているとき、読み取ったデータやデータベースにデータを挿入したときに文字化けして表示されることがあるのは本当に憂鬱なことですが、最近私は良い処理方法を探して、皆さんに参考にしてもらいました.
データベースからデータを読み出す場合はISO 8859からエンコードします.1 GBKに変換:ISO 2 GBK(String a)メソッドを呼び出します.
データベースにデータを挿入する場合は、GBKからISO 8859に符号化を変換します.1:GBK 2 ISO(String b)メソッドを呼び出します.
データベースからデータを読み出す場合はISO 8859からエンコードします.1 GBKに変換:ISO 2 GBK(String a)メソッドを呼び出します.
データベースにデータを挿入する場合は、GBKからISO 8859に符号化を変換します.1:GBK 2 ISO(String b)メソッドを呼び出します.
public class EncodingConvert {
public String ISO2GBK(String s){
String ns = null;
if (s == null)
return ns;
byte[] nbyte = s.getBytes();
// GBK ,
if(nbyte.length>1 && isGBK(nbyte[0],nbyte[1]))
return s;
//
try {
ns = new String(s.getBytes("iso8859_1"), "GBK");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
return ns;
}
/**
* GBK ISO
* @param s String
* @return String
*/
public String GBK2ISO(String s){
String ns = null;
if (s == null)
return ns;
byte[] nbyte = s.getBytes();
// GBK ,
if(nbyte.length>1 && (!isGBK(nbyte[0],nbyte[1])))
return s;
try {
ns = new String(s.getBytes("gbk"), "ISO-8859-1");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
return ns;
}
/**
*
* GBK
* @param head byte
* @param tail byte
* @return boolean
*/
public boolean isGBK( byte head,byte tail ){
int iHead = head & 0xff;
int iTail = tail & 0xff;
return ((iHead>=0x81 && iHead<=0xfe &&
(iTail>=0x40 && iTail<=0x7e ||
iTail>=0x80 && iTail<=0xfe)) ? true : false);
}
/**
* GB2312
*
* @param head byte
* @param tail byte
* @return boolean
*/
public boolean isGB2312( byte head,byte tail ){
int iHead = head & 0xff;
int iTail = tail & 0xff;
return ((iHead>=0xa1 && iHead<=0xf7 &&
iTail>=0xa1 && iTail<=0xfe) ? true : false);
}
}