Java automatically identifies the encoding of text files uploaded by users
We often encounter Garbled text files uploaded by users, and cannot limit the encoding format of uploaded files (which may be high for customers). We have to find a solution. I found a part of java to get the file encoding.
Or identify the error. or there is only a small piece of code, not to mention the specific reference... let me share it here. the tool class is just a method. I will not write the main test method.
It seems that you cannot upload attachments... just get it to my resources.
Referenced. These two jar classes.
Chardet. jar
Cpdetector_1.0.10.jar
Package com. dxx. buscredit. common. util; import info. monitorenter. cpdetector. io. ASCIIDetector; import info. monitorenter. cpdetector. io. codepageDetectorProxy; import info. monitorenter. cpdetector. io. JChardetFacade; import info. monitorenter. cpdetector. io. parsingDetector; import info. monitorenter. cpdetector. io. unicodeDetector; import java. io. file; import java. nio. charset. charset; public class FileCharsetDetector {/*** obtains the file encoding format using the third-party open-source package cpdetector. * @ param filePath * @ return */public static String getFileEncode (File file ){/**** 1. cpDetector has built-in common detection implementation classes. Instances of these detection implementation classes can be added using the add method. * For example, ParsingDetector, JChardetFacade, ASCIIDetector, and UnicodeDetector. * 2. The detector follows the principle of "who first returns non-null test results, this result prevails. * 3. cpDetector is based on statistical principles and cannot be completely correct. *
*/CodepageDetectorProxy detector = CodepageDetectorProxy. getInstance (); detector. add (new ParsingDetector (false); detector. add (UnicodeDetector. getInstance (); detector. add (JChardetFacade. getInstance (); // chardet is referenced internally. jar class detector. add (ASCIIDetector. getInstance (); Charset charset = null; try {charset = detector. detectCodepage (file. toURI (). toURL ();} catch (Exception e) {e. printStackTrace ();} // GBKStr by default Ing charsetName = "GBK"; if (charset! = Null) {if (charset. name (). equals ("US-ASCII") {charsetName = "ISO_8859_1";} else {charsetName = charset. name () ;}} return charsetName ;}}