Append a string to the end of the Java file

Source: Internet
Author: User

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

Related Article

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.