[英]Check if a String contains characters which aren't UTF-8 encoded in Java
[英]How to validate if a UTF-8 string contains mal-encoded characters
在大型数据集中,我有一些看起来像这样的数据:
"guide (but, yeah, it’s okay to share it with ‘em)."
我已经在十六进制编辑器中打开文件并通过字符编码检测算法( http://code.google.com/p/juniversalchardet/ )运行原始字节数据,并且它被正面检测为UTF-8。
在我看来,数据源错误地解释了原始字符集,并将有效的UTF-8写为我收到的输出。
我想尽我所能验证数据。 是否有任何启发式/算法可以帮助我进行验证?
一旦你有了字符串就不能这样做,你必须在你仍然有原始输入时这样做。 一旦你的字符串,就没有办法来自动分辨是否’
竟是打算输入而不一些严重的脆弱测试。 例如:
public static boolean isUTF8MisInterpreted( String input ) {
//convenience overload for the most common UTF-8 misinterpretation
//which is also the case in your question
return isUTF8MisInterpreted( input, "Windows-1252");
}
public static boolean isUTF8MisInterpreted( String input, String encoding) {
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
CharsetEncoder encoder = Charset.forName(encoding).newEncoder();
ByteBuffer tmp;
try {
tmp = encoder.encode(CharBuffer.wrap(input));
}
catch(CharacterCodingException e) {
return false;
}
try {
decoder.decode(tmp);
return true;
}
catch(CharacterCodingException e){
return false;
}
}
public static void main(String args[]) {
String test = "guide (but, yeah, it’s okay to share it with ‘em).";
String test2 = "guide (but, yeah, it’s okay to share it with ‘em).";
System.out.println( isUTF8MisInterpreted(test)); //true
System.out.println( isUTF8MisInterpreted(test2)); //false
}
如果您仍然可以访问原始输入,则可以看到字节数组是否相当于完全有效的utf-8字节序列:
public static boolean isValidUTF8( byte[] input ) {
CharsetDecoder cs = Charset.forName("UTF-8").newDecoder();
try {
cs.decode(ByteBuffer.wrap(input));
return true;
}
catch(CharacterCodingException e){
return false;
}
}
您还可以将CharsetDecoder与流一起使用,默认情况下,只要它在给定编码中看到无效字节,就会抛出异常。
如果您使用的是HTML5,那么只需在<head>
添加<meta charset="UTF-8">
<head>
for HTML4 <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.