我们有只支持 UTF-8 字符集的旧 mySQL 数据库。 Java 中是否有一种方法可以检测给定字符串是否与 UTF-8 兼容?
最佳答案
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;
}
这可能会更频繁地失败。
关于java - 检查字符串是否与 mySQL 兼容 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21866231/