Java UTF-8 file read/write

Source: Internet
Author: User

Scenario:

Read the UTF-8-encoded template file into the memory, and then convert it to an HTML file.

 

Note:

UTF-8 encoded files start with three additional Bytes: 0xef 0xbb 0xbf

A Unicode-encoded file starts with two additional Bytes: 0xff 0xfe (little endian) or 0xfe 0xff (big endian)

No additional bytes for ANSI Encoding

If the read and write operations are improper, the expected results may not be obtained (HTML displays garbled characters)

 

Read example:

 String readfile (string utf8file) {</P> <p> reader streamreader = new inputstreamreader (New fileinputstream (utf8file), "UTF-8 "); </P> <p> reader = new bufferedreader (streamreader); </P> <p> string line = NULL; </P> <p> stringbuilder text = new stringbuilder (); </P> <p> while (line = reader. readline ())! = NULL) {</P> <p> text. append (line); </P> <p >}</P> <p> reader. close (); </P> <p> return text. tostring (); </P> <p >}< br/>

 

 

Write example:

String template = readfile ("C: // utf8.template"); </P> <p> string outputfile = "C: // utf8.htm "; <br/> writer = new printwriter (<br/> New outputstreamwriter (New fileoutputstream (outputfile), "UTF-8"); </P> <p> template = template. replace ("$ title $", "UTF-8 read and write"); </P> <p> writer. write (Template); <br/> writer. close (); </P> <p>

 

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.