How to detect which character set encoding in Java?

China☆狼群 提交于 2019-12-23 08:35:53

问题


Does anybody know if there is a simple way to detect character set encoding in Java? It seems to me that some programs have the ability to detect which character set a given piece of data uses, or at least make an aproximation.

I suppose the underlying mechanism would have to decode the data in each character set and pick whichever one has the least undefined characters followed by which character set is more common to break a tie.

Any ideas?


回答1:


For finding whether data is in any unicode format( UTF-8,UTF-16... etc) you can read the data in byte stream and check the first 4 bytes( BOM size) , and for each encoding it will be different

for eg:

for UTF-8 first 3 bytes will be EF,BB,BF

for encodings other than unicode encodings i am not sure...




回答2:


Take a look at jchardet, a library ported from the Mozilla browser that specializes in "guessing" the charset of a document.

As an alternative, the cpdetector library, a bit newer, specializes in detecting the code page of a document.



来源:https://stackoverflow.com/questions/2248723/how-to-detect-which-character-set-encoding-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!