BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Append to a file in java using BufferedWriter, PrintWriter, FileWriter

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In this tutorial we will learn how to append content to a file in Java. There are two ways to append:

1) Using FileWriter and BufferedWriter: In this approach we will be having the content in one of more Strings and we will be appending those Strings to the file. The file can be appended using FileWriter alone however using BufferedWriter improves the performance as it maintains a buffer.
2) Using PrintWriter: This is one of best way to append content to a file. Whatever you write using PrintWriter object would be appended to the File.

1) Append content to File using FileWriter and BufferedWriter

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

class AppendFileDemo
{
   public static void main( String[] args )
   {	
      try{
    	String content = "This is my content which would be appended " +
        	"at the end of the specified file";
        //Specify the file name and path here
    	File file =new File("C://myfile.txt");

    	/* This logic is to create the file if the
    	 * file is not already present
    	 */
    	if(!file.exists()){
    	   file.createNewFile();
    	}

    	//Here true is to append the content to file
    	FileWriter fw = new FileWriter(file,true);
    	//BufferedWriter writer give better performance
    	BufferedWriter bw = new BufferedWriter(fw);
    	bw.write(content);
    	//Closing BufferedWriter Stream
    	bw.close();

	System.out.println("Data successfully appended at the end of file");

      }catch(IOException ioe){
         System.out.println("Exception occurred:");
    	 ioe.printStackTrace();
       }
   }
}

Output:

Data successfully appended at the end of file

Lets say myfile.txt content was:

This is the already present content of my file

After running the above program the content would be:

This is the already present content of my fileThis is my content which 
would be appended at the end of the specified file

2) Append content to File using PrintWriter

PrintWriter gives you more flexibility. Using this you can easily format the content which is to be appended to the File.

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

class AppendFileDemo2
{
   public static void main( String[] args )
   {	
      try{
          File file =new File("C://myfile.txt");
    	  if(!file.exists()){
    	 	file.createNewFile();
    	  }
    	  FileWriter fw = new FileWriter(file,true);
    	  BufferedWriter bw = new BufferedWriter(fw);
    	  PrintWriter pw = new PrintWriter(bw);
          //This will add a new line to the file content
    	  pw.println("");
          /* Below three statements would add three 
           * mentioned Strings to the file in new lines.
           */
    	  pw.println("This is first line");
    	  pw.println("This is the second line");
    	  pw.println("This is third line");
    	  pw.close();

	  System.out.println("Data successfully appended at the end of file");

       }catch(IOException ioe){
    	   System.out.println("Exception occurred:");
    	   ioe.printStackTrace();
      }
   }
}

Output:

Data successfully appended at the end of file

Lets say myfile.txt content was:

This is the already present content of my file

After running the above program the content would be:

This is the already present content of my file
This is first line
This is the second line
This is third line

References:

  • FileWriter – JavaDoc
  • BufferedWriter – JavaDoc
  • PrintWriter – Javadoc

Top Related Articles:

  1. how to copy one hashmap content to another hashmap
  2. Java StringBuffer class With Examples
  3. How to write to a file in java using FileOutputStream
  4. How to get the last modified date of a file in java
  5. Java – How to convert StringBuffer to String

Tags: Java-IO

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Vatsal Srivastava says

    May 3, 2015 at 10:12 PM

    Thank you so much Sir! I was actually creating a program in which I needed to create a file once and for all and keep adding data later. But somehow it always created a new file whenever I executed it. My problem is finally solved. Thank you very very very much Sir!!!

    Reply
  2. sateesh says

    February 5, 2016 at 6:35 PM

    Using FileWriter can i write the key value pair(username = “login_data”) data to a (properties) “config.properties” file instead of .txt file.

    Thanks in advance :)

    Reply
  3. jeet vyas says

    March 8, 2017 at 7:44 AM

    how can we download the appended file back sir

    Reply
    • john doe says

      October 22, 2017 at 7:43 PM

      You mean read it back into the program? See this:

      https://beginnersbook.com/2014/01/how-to-read-file-in-java-bufferedinputstream/

      Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap