I believe most people know that TXT file has four encoding formats, "GBK", "UTF-8", "Unicode", "utf-16be", each encoding format is different from the information written to the header. In order to avoid the phenomenon of reading garbled text, We should read the header information before reading the text in order to make the correct read encoding. The method is given below.
/** * To determine the encoding format of the file * @param filename:file * @return File Encoding format * @throws Exception/public static string codestring (String fil ename) throws exception{Bufferedinputstream bin = new Bufferedinputstream (new FileInputStream (fileName)); int p = (BIN.R EAD () << 8) + bin.read (); String code = NULL; Switch (p) {Case 0xefbb:code = ' UTF-8 '; break, case 0xfffe:code = ' Unicode '; break, case 0xfeff:code = ' utf-16be '; Bre Ak Default:code = "GBK"; } return code; }
Then, the text is read as a stream of characters
FileInputStream Finputstream = new FileInputStream (file)//code the encoding returned in the above method InputStreamReader InputStreamReader = New InputStreamReader (Finputstream, code); BufferedReader in = new BufferedReader (InputStreamReader); String strtmp = ""; Read by line while ((strtmp = In.readline ())!= null) {sbuffer.append (strtmp + "n");} return sbuffer.tostring ();