Java Tip: Append a text to a file

Here the simple tip, how to append text to a file.

package ojitha.blogspot.com.au;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Append to the file.
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        try {
            PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter("test.txt",true)));
            //PrintWriter printWriter = new PrintWriter("test.txt"); // not the way
            printWriter.printf("Hello, how are you %s day!\n",new Date().toString());
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above code, the true parameter in the FileWriter constructor enable to append to the file instead create new one again.

Written with StackEdit.

Comments

Popular posts from this blog

How To: GitHub projects in Spring Tool Suite

Spring 3 Part 7: Spring with Databases

Parse the namespace based XML using Python