How to append text to existing File in Java? Example

In the last tutorial, you have learned how to write data to a file in Java, and in this tutorial, you will learn how to append text to a file in Java. What is the difference between simply writing to a file vs appending data to a file? In the case of writing to a file, a program can start writing from the start but in the case of appending text, you start writing from the end of the file. You can append text into an existing file in Java by opening a file using FileWriter class in append mode. You can do this by using a special constructor provided by FileWriter class, which accepts a file and a boolean, which if passed as true then open the file in append mode. 

This means you can write new content at the end of the file. One of the common examples of appending text to file is logging but for that, you don't need to write your own logger, there are several good logging libraries available in Java world e.g. Log4j, SLF4j, Logbak, and even java.util.logging is good enough.

In this tutorial, you will learn how to append data to an existing text file from a Java program. As I said previously, if you are starting fresh in Java then I suggest you to better follow a book because they provide comprehensive coverage, which means you can learn a lot of things in a quick time.

You can follow either core Java by Cay S. Horstmann or Java: A Beginners Guide by Herbert Schildt, both are very good books and highly recommended for beginners in Java. A good point about a beginner's guide is that it also covers Java 8 while core Java 9th Edition only covers up to Java 7.




Java Program to append text to existing File

Here is our complete Java example to demonstrate how to append text to a file in Java. This program shows an example using both Java SE 6 code and Java SE 7 code by using a new feature try-with-resource statement to automatically close the resource.

In both examples, the key point to understand is opening the file using FileWriter in append mode. There is a special constructor for that which accepts a boolean argument to open the file in append mode.

FileWriter is a class from java.io package to write data into a file one character at a time, as we have seen earlier, it's better to wrap FileWriter inside BufferedWriter and PrintWriter for efficient and convenient writing into the file.

How to append text to file in Java with example


In this program, we have a file called names.txt, which is at the root of the classpath, inside the project directory of Eclipse IDE. This file contains two names at the beginning and after we run our program next set of names will be appended to it e.g. added at the end of the file. 

Since we are doing append two times, first by using Java 6 code and second by using Java SE 7 code, you will see a couple of names appended to file.

package filedemo;

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

/**
 * How to append data to a file in Java using FileReader.
 * 
 * @author java67
 */

public class FileAppendDemo{

    public static void main(String args[]) throws IOException {

        // We have a file names.txt which already contain
        // two names, now we need to append couple of
        // more names onto it.
        // here is how it looks like now
        // names.txt
        // James
        // Hobert

        // In order to append text to a file, you need to open
        // file into append mode, you do it by using
        // FileReader and passing append = true
        FileWriter fw = null;
        BufferedWriter bw = null;
        PrintWriter pw = null;

        try {
            fw = new FileWriter("names.txt", true);
            bw = new BufferedWriter(fw);
            pw = new PrintWriter(bw);

            pw.println("Shane");
            pw.println("Root");
            pw.println("Ben");

            System.out.println("Data Successfully appended into file");
            pw.flush();

        } finally {
            try {
                pw.close();
                bw.close();
                fw.close();
            } catch (IOException io) {// can't do anything }
            }

        }

        // in Java 7 you can do it easily using try-with-resource
        // statement as shown below

        try (FileWriter f = new FileWriter("names.txt", true);
                BufferedWriter b = new BufferedWriter(f);
                PrintWriter p = new PrintWriter(b);) {

            p.println("appending text into file");
            p.println("Gaura");
            p.println("Bori");

        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}


Output :
Data Successfully appended into file

File after appending text :
James
HobertShane
Root
Ben
appending text into a file
Gaura
Bori

From the output, it's clear that our program is working as expected. In the first example, Shane is added just next to Hobert because there was no new line there. Later since we have used PrintWriter, newline characters e.g. \n are automatically appended after each line.

Steps to append text to a file In Java 6

  1. Open the file you want to append text using FileWriter in append mode by passing true
  2. Wrap FileWriter into BufferedReader if you are going to write large text
  3. Wrap PrintWriter if you want to write in a new line each time
  4. Close FileWriter in finally block to avoid leaking file descriptors


Steps to append data into existing file In Java 7

  1. Use try-with-resource statement to open resources e.g. FileWriter, BufferedWriter, and PrintWriter
  2. Just write content using the println() method of PrintWriter
  3. The resource will be closed automatically when the control will leave the try block. If there is any exception thrown from the try block then that will be suppressed. 

Things to remember while appending text to existing File in Java

When appending text to an existing file in Java, there are several important considerations to keep in mind to ensure accurate and reliable file modifications, here few things which you can learn and remember while appending text to an existing file in Java:

1. File Path and Access
Verify that the file path is correct and that the program has the necessary permissions to read and write to the file.

2. File Existence
Ensure that the file you are trying to append to actually exists. If the file doesn't exist, you may need to handle this scenario by creating the file first or taking appropriate actions.

3. FileWriter and BufferedWriter
Use FileWriter in conjunction with BufferedWriter for efficient text appending. This combination helps in reducing I/O operations and improving performance.

4. FileWriter Constructor
When creating the FileWriter, consider using the constructor that allows you to specify whether you want to append to the file (new FileWriter(file, true)). This ensures that existing content is preserved, and new content is added at the end.

5. Handling IOException
Always handle potential IOExceptions that may occur during file operations. This involves using try-catch blocks or declaring the method with throws IOException in its signature.

6. Closing Resources
Close the FileWriter and BufferedWriter resources explicitly using the close() method to release system resources and ensure that the data is properly flushed to the file.

That's all about how to append text into an existing file in Java. You can use FileWriter to open the file for appending text as opposed to writing text. The difference between them is that when you append data, it will be added at the end of the file. Since FileWriter writes one character at a time, it's better to use BufferedWriter class for efficient writing. 

You can also use PrintWriter if you want to use its convenient print() and println() method for writing lines into the file but it's not necessary to write text at the end of the file.

3 comments:

  1. You can also use following code to append content to a file in Java 8, it's much easier and looks clean:

    Files.write(path, content.getBytes(charset), StandardOption.APPEND);

    or

    Files.write(path, lines, charset, StandardOptiona.APPEND)

    where path is instance of Path class which encapsulate a String path to the file
    lines is text, and charset is character encoding.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.