public static boolean isValidUTF8(String text) {
try {
byte[] bytes = text.getBytes("ISO-8859-1"); // 使用ISO-8859-1读取原始字节
String decoded = new String(bytes, "UTF-8"); // 尝试解码为UTF-8
String reEncoded = new String(decoded.getBytes("UTF-8"), "ISO-8859-1");
return text.equals(reEncoded); // 如果重新编码后的结果一致,说明没有乱码
} catch (UnsupportedEncodingException e) {
return false;
}
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme