Java automatically identifies the encoding of text files uploaded by users, and java text files
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 {/*** Use the third-party open-source package cpdetector to obtain the file encoding format. * @ param filePath * @ return */public static String getFileEncode (File file) {/*** <pre> * 1. cpDetector has built-in common test implementation classes, examples of these probe implementation classes can be added through 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. * </pre> */CodepageDetectorProxy detector = CodepageDetectorProxy. getInstance (); det Ector. 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 ();} // The default value is GBKString charsetName = "GBK"; if (charset! = Null) {if (charset. name (). equals ("US-ASCII") {charsetName = "ISO_8859_1";} else {charsetName = charset. name () ;}} return charsetName ;}}