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.