Two ways to append content to the end of a Java file

Source: Internet
Author: User

Java development, occasionally encountered at the end of the file to append the contents of the file, there are actually many ways to achieve, a brief introduction of two:

One is implemented by the Randomaccessfile class, and the other by the FileWriter class.

The implementation method is very simple, there is nothing to say, look directly at the code:

1      Public Static voidMain (string[] args)throwsException {2File file=NewFile (filename);3Randomaccessfile raf=NewRandomaccessfile (file, "RW");4          //moves the write file pointer to the end of the file. 5 Raf.seek (Raf.length ());6Raf.writebytes ("First Test randomaccessfile append \ r \ n");7 raf.close ();8FileWriter writer =NewFileWriter (file,true);9Writer.write ("Test randomaccessfile append \ r \ n");Ten writer.close (); OneTA =NewRandomaccessfile (file, "RW"); A          //moves the write file pointer to the end of the file.  - Raf.seek (Raf.length ()); -Raf.writebytes ("Second Test randomaccessfile append \ r \ n"); the raf.close (); -}

Finally view the contents of the file:

It's so simple .....

Two ways to append content to the end of a Java file

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.