codescracker
java

Java Program to Append Text to an Existing File



« Java Tutorial Java Examples »

I've created this article to cover some programs in Java to append some text or string to an existing file. Let's start with very basic one.

What to Do before Program ?

Since the program given below is used to append some new text to an existing file, therefore we must have a file say codescracker.txt available in the current directory. Therefore I'm going to create a file with some text.

Now I've create the file named codescracker.txt with its text as I'm the old content. and saved the file inside the current directory (the directory where the Java program or source code is saved). Here is the snapshot of the opened file:

java append text to existing file

Now let's move on, and create a Java program that appends some new text to this newly created file.

Appending Text to a File in Java

The question is, write a Java program to append text to an existing file. The program given below is the answer to this question. This is the very basic version of the program.

import java.io.*;

public class CodesCracker
{
   public static void main(String args[])
   {
      try
      {
         FileWriter fw = new FileWriter("codescracker.txt", true);
         fw.write("\nI'm the new content.");
         fw.close();
         System.out.println("The content is successfully appended to the file.");
      }
      catch(IOException ioe)
      {
         System.out.print("\nSomething went wrong!");
      }
   }
}

If you run or execute the above program, then here is the sample output you'll see on your output screen:

append text to existing file java

And after executing the above program, if you open and see the file codescracker.txt, then you'll see the text say I'm the new content. will available in the file without removing the previous. Here is the new snapshot of the same file:

java appending text to file

In above program, I've used \n before the text that is going to append, to append the text from new line. And the true as second parameter of FileWriter, is used to enable appending mode. If we remove the second parameter, then the previous text of the file will get removed and the new text will get written, instead of appending.

The following statement:

FileWriter fw = new FileWriter("codescracker.txt", true);

is enclosed inside the try block to catch the error or exception raised in some cases such as file doesn't exist, write operation is not allowed etc. Rest of the things are I thing self-understandable. Now let's move on to modify the above program.

Java Append Text to File - Complete Version

This is the complete version of the file append operation in Java. This program allows user to perform the operation based on his/her requirement. Multiple line of texts can also be appended to the file using this program. Do concentrate on the program to get some extra knowledge on the topic.

import java.io.*;
import java.util.Scanner;

public class CodesCracker
{
   public static void main(String args[])
   {
      String filename, line="", content="";
      char ch;
      int totLine, i;
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the Name of File: ");
      filename = scan.nextLine();
      
      while(true)
      {
         try
         {
            FileReader fr = new FileReader(filename);
            BufferedReader br = new BufferedReader(fr);
            System.out.println("\n----Content of File----");
            while((line = br.readLine()) != null)
            {
               System.out.println(line);
            }
            br.close();
            System.out.print("\nWant to append the text (y/n) ? ");
            ch = scan.next().charAt(0);
            if(ch=='y')
            {
               System.out.println("\n1. Append Single Line of Text.");
               System.out.println("2. Append Multiple Line of Text.");
               System.out.print("Enter Your Choice (1 or 2): ");
               ch = scan.next().charAt(0);
               if(ch=='1')
               {
                  Scanner s = new Scanner(System.in);
                  System.out.print("\nEnter the Text: ");
                  line = s.nextLine();
                  try
                  {
                     FileWriter fw = new FileWriter(filename, true);
                     fw.write("\n");
                     fw.write(line);
                     fw.close();
                     System.out.println("\nThe content is successfully appended to the file.");
                  }
                  catch(IOException ioe)
                  {
                     System.out.print("\nSomething went wrong!");
                  }
               }
               else if(ch=='2')
               {
                  Scanner s = new Scanner(System.in);
                  System.out.print("\nHow many lines to write ? ");
                  totLine = s.nextInt();
                  System.out.print("Enter " +totLine+ " lines of text: ");
                  for(i=0; i<(totLine+1); i++)
                  {
                     line = s.nextLine();
                     if((i+1)<(totLine+1))
                        line = line + '\n';
                     content = content + line;
                  }
                  try
                  {
                     FileWriter fw = new FileWriter(filename, true);
                     fw.write(content);
                     fw.close();
                     System.out.println("\nThe content is successfully appended to the file.");
                  }
                  catch(IOException ioe)
                  {
                     System.out.print("\nSomething went wrong!");
                  }
               }
               else
               {
                  System.out.println("\nInvaid Choice!");
                  break;
               }
               System.out.print("\nWant to see the new content (y/s) ? ");
               ch = scan.next().charAt(0);
               if(ch!='y')
                  break;
            }
            else
            {
               break;
            }
         }
         catch(IOException ioe)
         {
            System.out.println("\nFile Not Found!");
         }
      }
   }
}

Here is its sample run with following user inputs:

The snapshot given below shows the sample run with these inputs:

java append text to file example

Since the whole, main part of the program, is enclosed within a while loop with its condition true. Therefore the execution of program continues, until you enter n or anything other than y to exit from the loop. Here is the continued sample run with some other inputs:

java program append to file

Since I've supplied n (not 'y') as choice, not to further append the text to the file, therefore the program execution discontinues.

Java Online Test


« Java Tutorial Java Examples »



© Copyright 2021. All Rights Reserved.

CodesCracker