Java reads and writes utf8 files

Source: Internet
Author: User

Reading and Writing files is one of the most common operations.CodeCopying fragments will not only affect the overall appearance. For this reason, I have independently written a file operation class. It is much easier to stick the code of this class before calling it.

Import Java. io. bufferedreader; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. outputstreamwriter; public class filemanager {public static string read (string filename, string encoding) {stringbuffer filecontent = new stringbuffer (); bufferedreader BR = NULL; try {BR = new bufferedreader (New inputstreamreader (New Fileinputstream (filename), encoding); string line = NULL; while (line = Br. Readline ())! = NULL) {filecontent. append (line. trim (); filecontent. append ("\ n") ;}} catch (exception e) {e. printstacktrace ();} finally {If (BR! = NULL) Try {BR. close ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}return filecontent. tostring ();} public static void write (string filecontent, string filename, string encoding) {outputstreamwriter OSW = NULL; try {OSW = new outputstreamwriter (New fileoutputstream (filename ), encoding); OSW. write (filecontent); OSW. flush ();} catch (exception e) {e. printstacktrace ();} fin Ally {If (OSW! = NULL) Try {OSW. Close ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}}

Call example:
Write filemanager. Write ("Hello, world! "," D: // test.txt "," UTF-8 ");
Read system. Out. println (filemanager. Read ("D: // test.txt", "UTF-8 "));

 Append file: Use fileoutputstream to set the second parameter to true when constructing fileoutputstream.

 

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.