How Java recognizes and reads text files with different encodings

Source: Internet
Author: User

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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.