Two Methods for Java to append data to the end of a File

Source: Internet
Author: User
Package cn.com; import java. io. fileWriter; import java. io. randomAccessFile; // Problem description: // Append content to the end of the file // Method 1: use the RandomAccessFile class // 1 to set the randomAccessFile mode to rw // 2 to move randomAccessFile (seek) to the end of the file // 3 to append data // 4 to close the stream // Method 2: use the FileWriter class // 1 to set the second parameter of the FileWriter constructor method to true. append/2 to the end to append data // 3 close the stream public class FileTest {public static void main (String [] args) {FileTest fileTest = new FileTest (); fileTest. addContentFirst ("F: \ temp.txt", "test1"); fileTest. addContentSecond ("F: \ temp.txt", "test2");} public void addContentFirst (String filePath, String newContent) {try {RandomAccessFile randomAccessFile = new RandomAccessFile (filePath, "rw"); long fileLength = randomAccessFile. length (); randomAccessFile. seek (fileLength); randomAccessFile. write (newContent. getBytes ("UTF-8"); randomAccessFile. close () ;}catch (Exception e) {}} public void addContentSecond (String filePath, String newContent) {try {FileWriter fileWriter = new FileWriter (filePath, true); fileWriter. write (newContent); fileWriter. close () ;}catch (Exception e ){}}}

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.