When Java does file output, it sometimes wants to append characters directly to the end of an existing file instead of writing from scratch, which can be done in the following three ways:
1 Packagetest; 2 ImportJava.io.File; 3 ImportJava.io.FileOutputStream; 4 ImportJava.io.FileWriter; 5 Importjava.io.IOException; 6 ImportJava.io.PrintWriter; 7 ImportJava.io.RandomAccessFile; 8 9 Public classFilerw {Ten Public Static voidMain (string[] a) { One //Way One: A Try { -FileOutputStream fos =NewFileOutputStream (NewFile ("D:\\abc.txt"),true ) ; -String str = "ABC \ n";//line break required at end of string the Fos.write (Str.getbytes ()); - Fos.close (); -}Catch(IOException e) { - E.printstacktrace (); + } - + //Way Two: A Try { atFileWriter FW =NewFileWriter ("D:\\abc.txt",true); -PrintWriter pw=NewPrintWriter (FW); -Pw.println ("Append content");//line breaks are not required at the end of a string - Pw.close (); - Fw.close (); -}Catch(IOException e) { in E.printstacktrace (); - } to + //Way Three: - Try { theRandomaccessfile rf=NewRandomaccessfile ("D:\\abc.txt", "RW"); *Rf.seek (Rf.length ());//move the pointer to the end of the file $Rf.writebytes ("Append a line again!\n");//line break required at end of stringPanax NotoginsengRf.close ();//Close File Stream -}Catch(IOException e) { the E.printstacktrace (); + } A the + } - $}
Append a string to the end of the Java file