- 由于Java字符串的length计算的是字符长度,而数据库的限制长度是字节数,为了防止报错,可以在Java程序中截取字符串的指定字节数长度
public static String getLenString(String content, int len) {
if (content == null || content.length() == 0) {
return content;
}
byte[] bytes = content.getBytes();
if (bytes.length > len) {
int tempLen = new String(bytes, 0, len).length();
content = content.substring(0, tempLen);
// 防止最后一个字符的长度不是一个字节数
if (content.getBytes().length > len) {
content = content.substring(0, tempLen - 1);
}
}
return content;
}