问题
I was wondering if there are known methods to detect (or give a best guess of) the encoding of a particular string in Java.
I know that you always need some additional meta-data to tell what the encoding is, and there are best practices etc., but the situation I'm in, I need to give the best approximation.
A solution -- or a pointer -- to programatically distinguishing between UTF-8 and UTF-16 is also welcome.
回答1:
The utf-8 encoding should be easy to verify:
UTF-8 strings can be fairly reliably recognized as such by a simple heuristic algorithm. from wikipedia
Take a look at this site to see the algorithm
回答2:
Look at ICU4J which includes a character detector
回答3:
Take a look at Apache Commons IO, in particular BOMInputStream.
来源:https://stackoverflow.com/questions/6781345/detect-or-best-guess-of-incoming-string-encoding-in-java