Recently responsible for processing a batch of file data, some files are very large ordinary text editor can not open, resulting in the unknown to the encoding. So I want to write a program to judge, share.
Principle:
By obtaining the first three bytes of the file, the first two bytes of Unicode encoding are fffe; The first two bytes encoded by the Unicode big endian are the first two bytes of the feff;utf-8 encoded EFBB;
Code:
Package com.xx.test;
Import Java.io.BufferedInputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
public class Encodetest {/** * @param args */public static void main (string[] args) {test ();
private static void Test () {String dir = ' d:/fbb/myworkspace_dw07/finaldb/';
String fileName = "Finaldb2013313-jzy-v001glasscom3243ac0f-f7fb-4517-9102-b5f1934536f7";
String fileName = "D:/fbb/myworkspace_dw07/common_glass.log";
try {String encoding = codestring (dir,filename);
System.out.println ("Encoding:" +encoding);
catch (Exception e) {e.printstacktrace (); }/** * Determine the encoding format of the file * @param filename:file * @return File Encoding format * @throws Exception * * Publ IC static string codestring (String dir,string fileName) throws exception{File File = new file (dir+filename)
;
if (File==null | |!file.exists ()) {System.out.println ("file does not exist ..." +file.getabsolutepath ());
return null;
}
Bufferedinputstream bin = new Bufferedinputstream (new FileInputStream (file));
int p = (bin.read () << 8) + bin.read ();
String code = NULL; 0XEFBB, 0xFFFE, 0xFEFF, 0x5c75 These are the previous two bytes of this file 16-digit switch (p) {Case 0xefbb:code
= "UTF-8";
Break
Case 0xfffe:code = "Unicode";
Break
Case 0xfeff:code = "Utf-16be";
Break Case 0x5c75:code = "ansi|
ASCII ";
break;
Default:code = "GBK";
} return code;
}
}