Last updated on April 20th, 2022 at 09:36 am

It is very easy to write content to a text file that is already have some amount of data using Java. All you have to do is add a boolean true like below. This is tested in Tomcat 10.

 FileWriter fileWriter = new FileWriter(fileName,true);

This code will create a file with the name output.txt in the real path of the deployed application.

We are defining the file using these variables. absoluteFooWebPath will get the real path and the fileName will be having the real path + “output.txt”

 String absoluteFooWebPath = getServletContext().getRealPath("/");
 System.out.println("Path is:- "+absoluteFooWebPath);
// The name of the file to open.
 String fileName = absoluteFooWebPath+"output.txt";

Complete Code

import java.io.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.annotation.*;  

@WebServlet("/savefile") // Configure the request URL for this servlet (Tomcat 7/Servlet 3.0 upwards) 
public class WriteData1 extends HttpServlet {
public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
           PrintWriter out = response.getWriter();
        String absoluteFooWebPath = getServletContext().getRealPath("/");
        System.out.println("Path is:- "+absoluteFooWebPath);
        // The name of the file to open.
        String fileName = absoluteFooWebPath+"output.txt";
 
        try {
            // Assume default encoding.
            FileWriter fileWriter = new FileWriter(fileName,true);
            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            // Note that write() does not automatically
            // append a newline character.
            bufferedWriter.newLine();
            bufferedWriter.write("Hello,");
            bufferedWriter.write(" This Is A New Line.");
            bufferedWriter.newLine();
            bufferedWriter.write("We are writing");
            bufferedWriter.write(" the text to the file");
                out.println("Data Has Been Written");
            // Always close files.
            bufferedWriter.close();
        }
        catch(IOException ex) {
            System.out.println(
                "Error writing to file '"
                + fileName + "'");
                        out.println("Error writing to file '"
                + fileName + "'");
            // Or we could just do this:
            // ex.printStackTrace();
        }
 
}
}

When you load the above servlet (http://server:8080/app/savefile)for the first time a file with the name output.txt will get created with the content that we have defined and when it is reloaded it will start appending the content instead of rewriting the whole file.

If you are seeing any error related to write/create file, please verify permission.

Output (File named output.txt got created)

hello % ls -rlt
total 24
drwxr-xr-x  3 webroot  admin   96 Apr 20 10:25 WEB-INF
-rw-r--r--  1 webroot  admin  170 Apr 20 10:27 index.html
-rw-r--r-- 1 webroot  admin  262 Apr 20 10:59 form.html
-rw-r-----  1 webroot  admin  128 Apr 20 12:03 output.txt

Leave a Reply

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