我们有旧的mySQL DB,它只支持UTF-8字符集.Java中是否有一种检测给定字符串是否与UTF-8兼容的方法?
发布于 2014-02-19 15:55:23
public static boolean isUTF8MB4(String s) {
for (int i = 0; i < s.length(); ++i) {
int bytes = s.substring(i, i + 1).getBytes(StandardCharsets.UTF_8);
if (bytes > 3) {
return true;
}
}
return false;
}上述实现似乎是最好的,但除此之外:
public static boolean isUTF8MB4(String s) {
for (int i = 0; i < s.length(); ) {
int codePoint = s.codePointAt(i);
int bytes = Character.charCount(codePoint);
if (bytes > 3) {
return true;
}
i += bytes;
}
return false;
}可能会更频繁地失败。
发布于 2014-02-19 10:22:22
每个字符串都是UTF-8兼容的.只要正确设置数据库和MySQL驱动程序中的编码,您就可以设置了。
唯一的缺点是UTF-8编码字符串的字节长度可能比.length()所说的要大。下面是一个函数的Java实现,用于度量一个字符串在编码到UTF-8之后将占用多少字节。
编辑:由于Saqib指出旧的MySQL实际上不支持UTF-8,而只支持BMP子集,所以您可以检查字符串是否包含BMP外部的string.length()==string.codePointCount(0,string.length())代码点("true“表示”所有代码点都在BMP中“),并使用string.replaceAll("[^\u0000-\uffff]", "")删除它们。
发布于 2015-06-05 10:24:43
MySQL 定义:
名为utf8的字符集每个字符最多使用三个字节,并且只包含BMP字符。
因此,这一职能应当发挥作用:
private boolean isValidUTF8(final String string) {
for (int i = 0; i < string.length(); i++) {
final char c = string.charAt(i);
if (!Character.isBmpCodePoint(c)) {
return false;
}
}
return true;
}https://stackoverflow.com/questions/21866231
复制相似问题