Non puoi farlo una volta che hai la stringa, devi farlo mentre hai ancora l'input raw. Una volta ottenuta la stringa, non è possibile stabilire automaticamente se ’
è stato effettivamente utilizzato come input senza alcuni test seriamente fragili. Per esempio:
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
}
Se hai ancora accesso a ingresso grezzo, è possibile vedere se un array di byte pari a pienamente validi UTF-8 sequenze di byte con questo:
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;
}
}
è anche possibile utilizzare il CharsetDecoder con flussi, per impostazione predefinita genera un'eccezione non appena vede byte non validi nella codifica data.
Qual è la fonte qui? Hai inviato i dati originali a detta fonte? Ad una prima occhiata direi che hai provato e premuto gli apostrofi cp-1252 senza che siano convertiti in equivalenti UTF-8 appropriati ... – fge
Devi mostrare come stai leggendo i dati particolari dal set di dati e come stai presentando i dati particolari all'utente finale/te stesso. Ad esempio, stai usando 'FileReader' per leggerlo e' System.out.println() 'per presentarlo? Devi dire a uno oa entrambi di utilizzare UTF-8 invece del set di caratteri predefinito della piattaforma che è riconoscibile come CP1252. – BalusC
Sembra un'origine dati UTF-8 (con U + 2019 '' 'codificato correttamente come ottetti' e2 80 99') decodificato usando la codifica Windows-1252 a byte singolo (dove vengono interpretati come i punti di codice U + 00e2 U + 20ac U + 2122 - ''. – McDowell