In the previous article to determine the TXT encoding, found that Utf-8 no BOM encoding format can not be detected.
When it cannot be detected (when the returned code is empty), use the method again.
/** * Pass in a file object, check the file encoding * * @param the file File object instance * @return The document encoding, if none, return null * @th Rows FileNotFoundException * @throws IOException */public String guessfileencoding (file file) throws Filenotfo Undexception, IOException {return guessfileencoding (file, new Nsdetector ()); }/** * <pre> * Get the encoding of the files * @param the file * File object instance * @param languagehint * The language hint area code @see #nsPSMDetector, the value is as follows: * 1:japanese * 2:chinese * 3 : Simplified Chinese * 4:traditional Chinese * 5:korean * 6:dont kn OW (default) * </pre> * * @return file encoding, eg:utf-8,gbk,gb2312 form (when uncertain, returns a sequence of possible character encodings), or null if none is returned * @throws FileNotFoundException * @throws IOException */public String guessfileencoding (file file, int languagehint) th Rows FileNotFoundException, IOException {return guEssfileencoding (file, new Nsdetector (Languagehint)); }/** * Get the encoding of the file * * @param file * @param det * @return * @throws FileNotFoundException * @t Hrows IOException */Private String guessfileencoding (file file, nsdetector det) throws FileNotFoundException, Ioex ception {//SET an observer ...//the Notify () would be called if a matching charset is found. Det. Init (New Nsicharsetdetectionobserver () {public void Notify (String charset) {encoding = CharSet ; Found = true; } }); Bufferedinputstream imp = new Bufferedinputstream (new FileInputStream (file)); byte[] buf = new byte[1024]; int Len; Boolean done = false; Boolean isascii = false; while (len = Imp.read (buf, 0, buf.length))! =-1) {//Check if the stream is only ASCII. Isascii = Det.isascii (buf, Len); if (ISASCII) {break; }//DoIt if non-ascii and not do yet. Done = Det. DoIt (buf, Len, false); if (done) {break; }} imp.close (); Det. Dataend (); if (isascii) {encoding = "ASCII"; Found = true; } if (!found) {string[] prob = Det.getprobablecharsets (); Here the possible character sets are combined to return for (int i = 0; i < prob.length; i++) {if (i = = 0) {en coding = Prob[i]; } else {encoding + = "," + prob[i]; }} if (Prob.length > 0) {//In the absence of a discovery, you can only take the first possible encoding, which returns a possible sequence return encoding; } else {return null; }} return encoding; }
Java read different encoded TXT file Chinese garbled two