Wednesday, July 27, 2022

How to append text into File in Java – FileWriter Example

As a Java developer we often need to append text into File in Java instead of creating a new File, for example log files where every message is written into same file or appended at the end of the file. Thankfully Java File API is very rich and it provides several ways to append text into File in Java. Previously we have seen how to create files and directories in Java and how to read and write to a text file in Java and in this Java IO tutorial we will see how to append text into files in Java. We are going to use the standard FileWriter and  BufferedWriter approach to append text to File. One of the key points to remember while using FileWriter in Java is to initialize FileWriter to append text i.e. writing bytes at the end of the File rather than writing at the beginning of the File.

In next the section, we will see a complete Java program to append text into File in Java.  By the way, you can also use FileOutputStream instead of FileWriter if you would like to write bytes, instead of text. 

Similar to FileWriter, FileOutputStream constructor also takes a boolean append argument to open a connection to append bytes into File in Java.

How to append text into File in Java – FileWriter Example




Java program to append text to File in Java using FileWriter

How to append text to File in Java using FileWriter exampleIn this section, we will see a fully functional Java program that appends text at the end of the File. In this program, we have used FileWriter and initialized it will append as true. For better performance, we have wrapped FileWriter into a BufferedWriter, Similar to wrapping FileInputStream into BufferedReader to read File line by line in Java

Since this is a test program we have not finally blocked to close connection and also instead of handling The exception we have thrown them to keep the code simple and readable. In production code, you should always close the File connection on finally block and be ready to handle FileNotFoundException and IOException in Java.



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

/**
 * Simple Java program to append content and text into File.
 * You can either use byte stream approach or character reader approach to append
 * text to File. Readers will be faster than Stream and its advised to use BufferedWriter
 * for better performance. Exception from code are thrown to improve the clarity of code,
 * In real word you should handle them properly.
 *
 * @author Javin Paul
 */

public class FileAppendTest{
 
 
    public static void main(String args[]) throws FileNotFoundException, IOException {
        //name of File on which text will be appended,
        //currently file contains only one line
        //as "This data is before any text appended into file."
        String path = "C:/sample.txt";      
     
        //creating file object from given path
        File file = new File(path);
     
        //FileWriter second the argument is for append if it true then FileWritter will
        //write bytes at the end of File (append) rather than the beginning of a file
        FileWriter fileWriter = new FileWriter(file,true);
     
        //Use BufferedWriter instead of FileWriter for better performance
        BufferedWriter bufferFileWriter  = new BufferedWriter(fileWriter);
        fileWriter.append("This text should be appended in File form Java Program");
     
        //Don't forget to close Streams or Reader to free FileDescriptor associated with it
        bufferFileWriter.close();
     
        System.out.println("Java Program for appending content into File has been completed");
         
    }
 
}

Output:
Original File Content: This data is before any text is appended into a file.
Modified File Content: This data is before any text appended into file.This text should be appended in File form Java Program  You can also append contents or bytes by using FileOutputStream, FileOutputStream(String path, boolean append) takes a boolean parameter to append into File, which will ensure that new bytes will be written at the end of File rather than at beginning of File.

That’s all on how to append text to File in Java.  It's a rather simple Java program with only one thing to keep in mind, initializing FileWriter with boolean append as true so that FileWriter writes content at the end of the file instead starts of the File.


Other Java IO tutorials from Javarevisited Blog

7 comments:

  1. This was great! After trying to wade through the Java Oracle documentation your post had THE answer I was looking for, stated so simply in a clear example. Thanks!

    ReplyDelete
  2. Here is another example of appending text to a file in Java, it also uses FileWriter class but with PrintWriter to append text line by line.

    ReplyDelete
  3. Could you please tell me how to append a text in nth cell in a row using FileWriter / PrintWriter ?

    ReplyDelete
  4. @Unknown, are you asking about XLS file which has concept of row and column? or do you mean just at nth position? If later is the case then its not supported by FileWriter or PrintWriter, you need to use RandomAccess file, which supports random access by allowing you to move file pointer to read and write at arbitrary position.

    ReplyDelete
  5. 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.

    By the way, is it possible to append text into an existing file using FileOutPutStream in Java?

    ReplyDelete
  6. If you read the article closely, you will find that similar to FileWriter, FileOutputStream constructor also takes a boolean parameter to open file in append mode. In this mode you can append new content at the end of file without losing old data.

    ReplyDelete