How to Append to a File In Java?

0 Flares 0 Flares ×

There are instances when you may have to append data to an existing file in your Java program. Though this is a simple task. sometimes developers get confused what to do. So here is a sample program that demonstrates how to append data to an existing file in Java.

You can easily append to a File in Java by using BufferedWriter and FileWrites classes. But the most important is creating the FileWriter constructor in proper way. In the constructor you need to set the append parameter as true, which instructs the program to append to the end of the file instead of overwriting the file with new content.

BufferedWriter bufWr = new BufferedWriter(new FileWriter(MY_FILE, true));

The Concept

  1. Create the instance of FileWriter with append mode as true.
  2. Create the instance of BufferedWriter.
  3. Write to the file and the flush.
  4. Close all resources.

Java Example to Append Data To an Existing File

Here we are gong to append data to an existing file mylog.txt with some new data. The existing file has the below data before appending data to it.

This is a sample text file.
package com.lessonslab.io.file;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class AppendContentToAFileInJava {
public static void main(String args[]) {
String MY_FILE = "/home/hduser/test/mylog.txt";
String content = "This is example of appending to a file in java";
BufferedWriter bufWr = null;
try
{
// Second parameter sets the append mode, set to true will append to the end of file
bufWr = new BufferedWriter(new FileWriter(MY_FILE, true));
bufWr.write(content);
bufWr.newLine();
bufWr.flush();
}
catch (IOException e)
{
System.out.println("Unable to write to file " + e.getLocalizedMessage());
}
finally
{
// always close the resources
if (bufWr != null)
{
try
{
bufWr.close();
}
catch (IOException e)
{
System.out.println("Unable to Close resource " + e.getMessage());
}
}
}
}
}

After executing the program our file mylog.txt has the below content:

This is a sample text file.
This is example of appending to a file in java

So this is one of the simplest way how we can append data to an existing file in Java program. However depending on situation and demand we can follow other ways of appending to a file.

Guru

+Ayodhyanath Guru holds a B.Tech degree in Electrical Engineering and has worked with various prestigious clients in the IT industry and presently working as a Software Engineer. He is a part time blogger and presently authors the Jafaloo.Com blog. Being a tech enthusiast Guru likes to surf the web and blogs about interesting technical topics like How-To guides, freewares, Tutorials, Software, Gadgets, web applications etc. Apart from blogging he likes coding in Java/J2EE and PHP.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 0 Flares ×