Replace Particular Words In a Text File in Java

In this instructional exercise, you will see how to replace particular words in a text File in java.

We will use the Java File Handling to perform this operation because to deal with the operations that are to be performed in a file we need file handling properties to access it and to manipulate any data into it.

You have to be familiar with some of the methods that we are going to use in this code. These are the FileWriter and the FileReader class. These two classes often used to compose and peruse information from content records.

Now, suppose we have a record in a text file named as “records.txt”- A record of id, name, and age just like you can see below:

1223,jack,29
3212,jerry,30
2646,raj,19
5465,anil,62

In this record, we have to change the details of those records whose id is 2646, change his name and age to shubham and 20 respectively. So let’s continue reading this post to learn…

The below code can be written to achieve this operation-

import java.io.File;
import java.util.Scanner;
public class EditRecord
{
    private static Scanner x;
    public static void main(String args[])
    {
        String filepath="records.txt";
        String editTerm="2646";
        String newID="6264";
        String newName="shubham";
        String newAge="20";
        
        editRecord(filepath,editTerm,newID,newName,newAge);
    }
    public static void editRecord(String filepath,String editTerm,String newID,String newname,String newAge)
    {
        String tempFile="temp.txt";
        File oldFile=new File(filepath);
        File newFile=new File(tempFile);
        String ID="";String name="";String age="";
        try
        {
            FileWriter fw=new FileWriter(tempFile,true);
            BufferedWriter bw=new BufferedWriter(fw);
            PrintWriter pw=new PrintWriter(bw);
            x=new Scanner(new File(filepath));
            x.useDelimeter("[,\n]");
            while(x.hasNext())
            {
                ID=x.next();
                name=x.next();
                age=x.next();
                if(ID.equals(editTerm))
                {
                    pw.println(newId+","+newName+","+age);
                }
                else
                {
                    pw.println(ID+","+name+","+age);
                }
            }
        x.close();
        pw.flush();
        pw.close();
        }
        catch(Exception e)
        {
            System.out.println("Error");
        }
    }
}
                      

The useDelimeter() method will allow you to put a regular expression string in the above code.

This will give the output as-

1223,jack,29
3212,jerry,30 
6264,shubham,20 
5465,anil,62

So, you can clearly see that we are able to successfully replace a specific word in a text file with Java.

Also, read:

 

Leave a Reply

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