1: simple judgment is a UTF-8 or not a UTF-8, because generally in addition to the UTF-8 is GBK, so set the default for GBK.
When a file is stored based on a given character set, encoding information may be stored in the first three bytes of the file. Therefore, the basic principle is to read the first three bytes of the file, determine the value of these bytes to know the encoding format. In fact, if the platform running the project is a Chinese operating system, if these text files are generated within the project, developers can control the text encoding format, as long as you determine the two common encoding can be: GBK and UTF-8. Because the default English Windows encoding is GBK, so generally as long as the determination of UTF-8 encoding format. For text files in UTF-8 encoding format, the value of the first three bytes is-17,-69,-65, so the code snippet to determine whether the UTF-8 encoding format is as follows:
File file = new file (PATH );
Inputstream in = new java. Io. fileinputstream (File );
Byte [] B = new byte [3];
In. Read (B );
In. Close ();
If (B [0] =-17 & B [1] =-69 & B [2] =-65)
System. Out. println (file. getname () + ": encoded as UTF-8 ");
Else
System. Out. println (file. getname () + ": it may be GBK or another code ");
With this method, as long as you know the encoding information stored in the file header, you can determine whether the file is in a certain encoding format. It is not limited to UTF-8. Note the limitations of this method: the file header must contain the file storage encoding information. For non-standard files or files that have been tampered with, let alone.
2: For more complex file encoding detection, you can use an open-source project cpdetector. Its website is http://cpdetector.sourceforge.net /. Its Class Library is very small and only about K. The cpdetector is based on the statistical principle and cannot be completely correct. The code for determining text files using this class library is as follows:
Read external files (use cpdetector to detect the file encoding format, and then read the file using the detected encoding method)
/*** Use the third-party open-source package cpdetector to obtain the file encoding format ** @ Param path * to determine the path of the source file in the file encoding format */public static string getfileencode (string path) {/** detector is a detector that submits a probe task to an instance of a specific probe implementation class. * Cpdetector has built-in common probe implementation classes. Examples of these probe implementation classes can be added through the add method, such as parsingdetector, * jchardetfacade, asciidetector, and unicodedetector. * The detector returns the * character set encoding that has been detected based on the principle of "who first returns the non-null test result, which prevails. Three third-party jar packages are required for use: anlr. jar, chardet. jar, and cpdetector. jar * cpdetector are based on statistical principles and are not guaranteed to be completely correct. */Codepagedetectorproxy detector = codepagedetectorproxy. getinstance ();/** parsingdetector can be used to check the encoding of HTML, XML, and other files or response streams. Parameters in the constructor are used to * Indicate whether to display detailed information about the probe process, false is not displayed. */Detector. Add (New parsingdetector (false);/** jchardetfacade encapsulates jchardet provided by Mozilla, which can complete encoding * Determination for most files. Therefore, this detector can meet the requirements of most projects. If you are not at ease, you can add more detectors, such as asciidetector and unicodedetector. */Detector. add (jchardetfacade. getinstance (); // anlr is used. jar, chardet. jar // asciidetector is used for ASCII encoding Determination of detector. add (asciidetector. getinstance (); // unicodedetector is used to determine the Unicode family encoding. add (unicodedetector. getinstance (); Java. NIO. charset. charset = NULL; file F = new file (PATH); try {charset = detector. detectcodepage (F. touri (). tourl ();} catch (exception ex) {ex. printstacktrace ();} If (charset! = NULL) return charset. name (); elsereturn NULL;} string charsetname = getfileencode (configfilepath); system. out. println (charsetname); inputstream = new fileinputstream (configfile); bufferedreader in = new bufferedreader (New inputstreamreader (inputstream, charsetname ));
Read the internal resource file of the jar package (use cpdetector to check the encoding format of the internal resource file of the jar, and then read the file in the detected encoding mode ):
/*** Use the third-party open-source package cpdetector to obtain the file encoding corresponding to the URL ** @ Param path * to determine the URL of the source file in the file encoding format */public static string getfileencode (URL) {/** detector is a detector that submits a probe task to an instance of a specific probe implementation class. * Cpdetector has built-in common probe implementation classes. Examples of these probe implementation classes can be added through the add method, such as parsingdetector, * jchardetfacade, asciidetector, and unicodedetector. * The detector returns the * character set encoding that has been detected based on the principle of "who first returns the non-null test result, which prevails. Three third-party jar packages are required for use: anlr. jar, chardet. jar, and cpdetector. jar * cpdetector are based on statistical principles and are not guaranteed to be completely correct. */Codepagedetectorproxy detector = codepagedetectorproxy. getinstance ();/** parsingdetector can be used to check the encoding of HTML, XML, and other files or response streams. Parameters in the constructor are used to * Indicate whether to display detailed information about the probe process, false is not displayed. */Detector. Add (New parsingdetector (false);/** jchardetfacade encapsulates jchardet provided by Mozilla, which can complete encoding * Determination for most files. Therefore, this detector can meet the requirements of most projects. If you are not at ease, you can add more detectors, such as asciidetector and unicodedetector. */Detector. add (jchardetfacade. getinstance (); // anlr is used. jar, chardet. jar // asciidetector is used for ASCII encoding Determination of detector. add (asciidetector. getinstance (); // unicodedetector is used to determine the Unicode family encoding. add (unicodedetector. getinstance (); Java. NIO. charset. charset = NULL; try {charset = detector. detectcodepage (URL);} catch (exception ex) {ex. printstacktrace ();} If (charset! = NULL) return charset. name (); elsereturn NULL;} URL url = createstationtreemodel. class. getresource ("/resource/" + "configuration file"); urlconnection = URL. openconnection (); inputstream = urlconnection. getinputstream (); string charsetname = getfileencode (URL); system. out. println (charsetname); bufferedreader in = new bufferedreader (New inputstreamreader (inputstream, charsetname ));
3: detects the encoding of any input text stream by calling its overload format:
Charset = detector. detectcodepage (the text input stream to be tested, which measures the number of bytes read from the stream );
The number of bytes is specified by the programmer. The more bytes, the more accurate the determination. Of course, the longer the time it takes. Note that the number of bytes cannot exceed the maximum length of the text stream.
4. Example of determining the file encoding: Property file (. properties) is a common text storage method in Java programs. Like the Struts framework, it uses string Resources in the property file storage program. Its content is as follows: # Comment statement Property name = property value The general method for reading attribute files is:
Fileinputstream IOS = new fileinputstream ("attribute file name ");
Properties prop = new properties ();
Prop. Load (IOS );
String value = prop. getproperty ("property name ");
IOS. Close ();
Although it is convenient to use the load method of Java. Io. properties to read the attribute file, if the attribute file contains Chinese characters, garbled characters will occur after reading the file. This is because the load method uses byte streams to read text. After reading, it needs to encode the byte stream into a string, and it uses the encoding "iso-8859-1", which is the ASCII character set, chinese encoding is not supported,Method 1: use explicit transcoding:
String value = prop. getproperty ("property name ");
String encvalue = new string (value. getbytes ("iso-8859-1"), "actual encoding of the property file ");
Method 2: If this property file is within the project, we can control the encoding format of the property file. For example, if the GBK defined in Windows is used, we can directly use "GBK" for transcoding, if you agree to use a UTF-8, use UTF-8 for direct transcoding.Method 3: If you want to be more flexible and enable automatic detection encoding, you can use the method described above to determine the encoding of attribute files to facilitate the work of developers. Supplement: You can use the following code to obtain the Java supported encoding set: Charset. availablecharsets (). keyset (); You can use the following code to obtain the default system encoding: Charset. defaultcharset ();