How to append content to file in Java

FileWritter, a character stream to write characters to file. By default, it will replace all the existing content with new content, however, when you specified a true (boolean) value as the second argument in FileWritter constructor, it will keep the existing content and append the new content in the end of the file.

1. Replace all existing content with new content.

new FileWriter(file);

2. Keep the existing content and append the new content in the end of the file.

new FileWriter(file,true);

Append file example

A text file named “javaio-appendfile.txt” and contains the following content.

ABC Hello

Append new content with new FileWriter(file,true)

package com.mkyong.file;
 
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
 
public class AppendToFileExample 
{
    public static void main( String[] args )
    {	
    	try{
    		String data = " This content will append to the end of the file";
 
    		File file =new File("javaio-appendfile.txt");
 
    		//if file doesnt exists, then create it
    		if(!file.exists()){
    			file.createNewFile();
    		}
 
    		//true = append file
    		FileWriter fileWritter = new FileWriter(file.getName(),true);
    	        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
    	        bufferWritter.write(data);
    	        bufferWritter.close();
 
	        System.out.println("Done");
 
    	}catch(IOException e){
    		e.printStackTrace();
    	}
    }
}

Result

Now, the text file “javaio-appendfile.txt” content is updated

ABC Hello This content will append to the end of the file

Reference

  1. http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: bottled alkaline water()

  • Pingback: pay day loans()

  • Pingback: water ionizers()

  • Pingback: water ionizer machine()

  • Pingback: laan penge online()

  • Pingback: car parking()

  • Pingback: 3gp mobile porn()

  • Pingback: stop parking()

  • Pingback: her og nu lan()

  • Pingback: DIRECTV channels()

  • Pingback: increaseleptin.com()

  • Pingback: Blue Coaster33()

  • http://forums.Ihatemountains.com/profile.php?id=4884 Valium

    Your own report offers established beneficial to me personally.

    It_s quite informative and you’re obviously very well-informed in this region. You possess opened my personal face for you to different views on this particular matter with intriguing and strong content material.

  • krish

    the below code not working for me untill I changed the following line:
    FileWriter fileWritter = new FileWriter(file.getName(),true);

    to this:

    FileWriter fileWritter = new FileWriter(file,true);

    Mkyong please modife the code

    • Mohammed Rukhsar

      In place of file.getName(),u use file.getPath() and after that u must pass that value.
      So it will be work.

      • Zenith

        Gr8!! That worked!! Thank you :)

  • Dave

    Hi, Thanks for the code snippet, it’s useful. It’s probably a good idea to wrap the bufferWritter.close(); in a finally block in case of any exceptions before then. This will prevent unclosed filehandles on the FS.

  • A.J

    Hi

    thanks for this code it truly saved me a lot of time and headache tablets loll

    Kind Regards
    A.J Bosch

  • Divyasree

    haii friends,
    Here why we have to pass the FileWriter variable to the BufferedWriter as argument??

  • http://faisalnet5.blogspot.com/ Faisal

    Don’t know why the given “Append file example” was not working for me untill I changed the following line:

    FileWriter fileWritter = new FileWriter(file.getName(),true);

    to this:

    FileWriter fileWritter = new FileWriter(file,true);
    • Nitesh Rajput
      <p> Same thing happening with me also,when i tried to append contents to existing file <br> by using 
      FileWriter fileWritter = new FileWriter(file.getName(),true) <br> it was not appending and also not giving any exception,but when i changed this with FileWriter fileWritter = new FileWriter(file,true); <br>
      Its running fine and giving actual result.
      • dannerman

        Yes damn it’s true!!!
        thank you for your reply, I got stuck in file.getName() !!!! :-(

    • jegadees

      yes, this has happened in my case too. anyway thank you mkyong

    • http://tanvietblog.com TanViet

      @Faisal: I have also same problem. Thank you!

  • Devi

    is it possible to concatenate two audio files in android?.please reply
    if any one knows solution for this.

  • Jerry

    I know this forum is old, so I hope you still can respond. This code works for me, except it writes the file to the current directory. I am trying to write the file to a specified directory. below is my code:

    The behavior of the code is as follows:
    1) The code creates a new directory(X)
    2) The code creates a new file(F) in that directory(X) – it is empty file
    3) The code creates another file(F2) in the current directory(X2)
    4) The code writes and appends data to the file(F2) in the current directory(X2)
    5) The file(F) created in the other directory(X) is left blank.

    The desired behavior is:
    1) The code creates a new directory(X)
    2) The code creates a new file(F) in that directory(X)
    3) The code writes and appends data to the file(F) in the current directory(X)

    try
                           {
     
                                   String strippedFile = null;
                                   String fs = null;
                                   //String currDir = new File(".")
                                   fs = file.toString();
                                   strippedFile = fs.substring(3,8);
                                   String data = DateFormat.getInstance().format(now) + "\n" + file + "\n####### NUMBER OF MACS: " + macCounter + "\n" + "####### UNIQUE MACS: " + uniqueMacs + "\n" + "####### NUMBER OF NON-NUMERIC TIMESTAMPS: " + counter + "\n" + "####### NUMBER OF CORRUPT DATES: " + badDate + "\n" + "####### DELTA FAILURES: " + deltaFailureCount + "\n" + "####### AVERAGE RSSI: " + averageRSSI + "\n" + "####### NUMBER OF GPS SYNC'S: " + gpsCounter + "\n\n";
     
     
                                   //System.out.println("DEBUG FILE NAME: " + strippedFile);
                                   File logFile = new File(".\\testreports\\report_" + strippedFile + ".txt");
     
                                   // if the file doesn't exist create one and write to it
                                   if(!logFile.exists())
                                   {
                                           logFile.createNewFile();
     
                                   }
     
                                   //file exists - append
                                   FileWriter fw = new FileWriter(logFile.getName(), true);
                                   BufferedWriter bw = new BufferedWriter(fw);
                                   bw.write(data);
                                   bw.close();
     
     
     
                               {
                                       System.out.println("file already exists");
                               }
                           }
                           catch(IOException e)
                           {
                                   e.printStackTrace();
                           }