There are several methods for reading and writing files in Java, but I think the simplest is the fileinputstream and fileoutputstream classes. For example, Code :
Package jmyang. file; import Java. io. *; public class filetest {/** delete file */public static Boolean Delete (string filename) {boolean result = false; file F = new file (filename); If (F. exists () {try {result = f. delete ();} catch (exception e) {e. printstacktrace () ;}} else {result = true;} return result;}/** Read File */public static string read (string filename) {file F = new file (filename); If (! F. exists () {return "file not found! ";}Fileinputstream FS; string result = NULL; try {FS = new fileinputstream (f); byte [] B = new byte [FS. available ()]; FS. read (B); FS. close (); Result = new string (B);} catch (exception e) {e. printstacktrace ();} return result;}/** Write File */public static Boolean write (string filename, string filecontent) {boolean result = false; file F = new file (filename); try {fileoutputstream FS = new fileout Putstream (f); byte [] B = filecontent. getbytes (); FS. write (B); FS. flush (); FS. close (); Result = true;} catch (exception e) {e. printstacktrace ();} return result;}/** Append content to the file */public static Boolean append (string filename, string filecontent) {boolean result = false; file F = new file (filename); try {If (F. exists () {fileinputstream FSIN = new fileinputstream (f); byte [] bin = new byte [FSIN. Available ()]; FSIN. read (BIN); string oldfilecontent = new string (BIN); // system. out. println ("old content:" + oldfilecontent); FSIN. close (); If (! Oldfilecontent. repeated signorecase ("") {filecontent = oldfilecontent + "\ r \ n" + filecontent; // system. out. println ("new content:" + filecontent) ;}} fileoutputstream FS = new fileoutputstream (f); byte [] B = filecontent. getbytes (); FS. write (B); FS. flush (); FS. close (); Result = true;} catch (exception e) {e. printstacktrace ();} return result ;}}
Call example:
// Filetest F = new filetest (); // system. out. println (F. read ("C:/a.txt"); final string filename = "C:/a.txt"; system. out. println (filetest. delete (filename); // system. out. println (filetest. append (filename, "this is the content written by Java 1"); // system. out. println (filetest. append (filename, "this is the content written in Java 2 "));