内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我有一些看起来像这样的数据:
"guide (but, yeah, it’s okay to share it with ‘em)."
我已经在十六进制编辑器中打开了文件,并通过字符编码检测算法(http://code.google.com/p/juniversalchardet/)运行原始字节数据,它被肯定检测为UTF-8。
在我看来,数据的来源错误地解释了原来的字符集,并写了有效的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,默认情况下,只要在给定编码中看到无效字节,就会抛出异常。