Share on Google+Share on Google+

How to Write to a File in Java without overwriting

This example code teaches you how to Write to a File in Java without overwriting.

Learn how to Write to a File in Java without overwriting in your Java program

This tutorial teaches you how to write to a file in Java without overwriting the existing content. This type of application is useful in writing the application log data into a file. In this this we have a "log.txt" file which already contains the data and our program will write to this file without overwriting the content of "log.txt" file. Next time if you write something to this file then the content will be appended to it.

In this program we are using the FileWriter class of the package.

Our examples code appends a line to the log.txt file when executed. Following is the code which appends the line to the log.txt file:

out.write("Line Added on: " + new java.util.Date()+"\n");

Our program uses the Java API for this purpose. The object of FileWriter is created using the following code:

FileWriter fstream = new FileWriter("log.txt",true);

Here is the syntax of the FileWriter class:

FileWriter(File file, boolean append)

The FileWriter class takes two parameters:

1. File file: the name of the file to be opened.

2. boolean append: If this parameter is true then the data is written to the end of the file. In other words it appends the data at the end of file.

So, if in your program you have a requirement to append the data into file then you should pass the true as parameter.

Here is the complete example code of the program:

class WriteToFileWithoutOverwriting 
 public static void main(String args[])
	  FileWriter fstream = new FileWriter("log.txt",true);
	  BufferedWriter out = new BufferedWriter(fstream);
	  out.write("Line Added on: " + new java.util.Date()+"\n");
  }catch (Exception e){
	 System.err.println("Error while writing to file: " +

To compile the program type following line on command prompt:


To execute the program type following on the command prompt:

java WriteToFileWithoutOverwriting

In the above program you have learned how to write code to to append the content in a text file through your Java program. Program explained here writes the content to a file (text file) without overwriting the content of the file. This type of program is very useful in writing log information to a file.



Posted on: April 28, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

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.

Discuss: How to Write to a File in Java without overwriting  

Post your Comment

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