今天檢驗一個字符串長度時出現了問題。我在數據庫(ORACLE)中定義的長度時VARCHAR2(50),
"附言字段測試1附言字段測試2附言字段測試3附言字段測試4",這是測試數據,一共52個字節,在插入到數據庫中報錯了,
但是在JAVA使用length()方法他的長度並沒有超過50,但在我的需求中他是超出的。JAVA中文是一個字符,但和字節不是1。
public static int getStringLen(String str,String codeType){
int reLn=0;
if(str==null||str.equals("")){
return reLn;
}
try {
// byte[] t_iso = str.getBytes("ISO8859-1");
byte[] t_gbk = str.getBytes("GBK");
byte[] t_utf8 = str.getBytes("UTF-8");
// System.out.println("使用ISO解碼..." + t_iso.length);
// System.out.println("使用GBK解碼..." + t_gbk.length);
// System.out.println("使用UTF8解碼..." + t_utf8.length);
if(codeType==null||codeType.equals("")){
return t_gbk.length;
}else if(codeType!=null&&codeType.equals("UTF-8")){
return t_utf8.length;
}
} catch (Exception e) {
}
return reLn;
}