Home Java Examples Io Java Write To File Append


Share on Google+Share on Google+

Java Write To File Append

In this tutorial you will learn how to append the text when you are writing in a text file.

Java Write To File Append

In this tutorial you will learn how to append the text when you are writing in a text file.

Appending a text means that the text that are written earlier or can say the old contents of an existing file should be retained when you are trying to write new contents in an existing files.

The example what I am going to give here will demonstrate you how to retain the older text when you are writing again to an existing file. To achieve the solution of this problem at first I have created a text file named "appenToFile.txt" and write some text. And then create a java file named WriteToFileAppend.java where I have used the FileWriter constructor to write a stream of characters. Argument 'true' of FileWriter constructor denotes that the contents of the file will be retained when you will try to write new text in an existing files.

Constructor of the FileWriter class that I have used in this example is as :

FileWriter(String fileName, boolean append);

e.g. FileWriter fw = new FileWriter("appenToFile.txt", true);

Example :


import java.io.*;

class WriteToFileAppend
  public static void main (String args[])
    WriteToFileAppend wtfa = new WriteToFileAppend();
    System.out.println("-----*----New text has been written into the existing file successfully----*-----");
   public void fileWithAppend()
     FileWriter fw = null;
     BufferedWriter bw = null;
       fw = new FileWriter("appenToFile.txt", true);
       bw = new BufferedWriter(fw);
       bw.write("These text are newly added.");              
      catch(Exception e)
        if (bw != null)
         catch (IOException ioe)

How to Execute this example :

After doing the basic process to execute a java program write simply on command prompt as :

javac WriteToFileAppend.java to compile the program

And after successfully compilation to run simply type as :

java WriteToFileAppend

Output :

When you will execute this example new contents that you are trying to write using java program in an existing file will be written with retaining the old texts.

1. An existing text file that contains the texts as follows :

2. An existing file into which new texts are written with retaining the old texts as follows :

Download Source Code


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 17, 2012

Related Tutorials

Ask Questions?    Discuss: Java Write To File Append  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image