Java program to replace string in a file

Java program to replace strings in a file :

In this tutorial, we will learn how to read strings from a file, how to modify the contents and then again write them back in the same file. We are not taking any inputs from the user. In this example, after reading the contents of the file, we are replacing all ‘new’ words with ‘old’. For example, if the file contain one string This is a new ball., after modification it will become This is a old ball. Let’s take a look into the program before moving into more details :

Java Program :

import java.io.*;

public class Main {

    public static final String STRING_A = "new";
    public static final String STRING_B = "old";

    public static void main(String[] args) throws java.lang.Exception {

        //1
        String originalFilePath = "C://sample.txt";
        String originalFileContent = "";

        //2
        BufferedReader reader = null;
        BufferedWriter writer = null;

        //3
        try {

            //4
            reader = new BufferedReader(new FileReader(originalFilePath));

            //5
            String currentReadingLine = reader.readLine();

            //6
            while (currentReadingLine != null) {
                originalFileContent += currentReadingLine + System.lineSeparator();
                currentReadingLine = reader.readLine();
            }

            //7
            String modifiedFileContent = originalFileContent.replaceAll(STRING_A, STRING_B);

            //8
            writer = new BufferedWriter(new FileWriter(originalFilePath));

            //9
            writer.write(modifiedFileContent);

        } catch (IOException e) {
            //handle exception
        } finally {
            //10
            try {
                if (reader != null) {
                    reader.close();
                }

                if (writer != null) {
                    writer.close();
                }

            } catch (IOException e) {
                //handle exception
            }
        }
    }

}

Explanation :

The commented numbers in the above program denotes the step number below :

  1. Create two String variables to hold the path of the file and to hold the content of the file. originalFilePath is the path of the file we are going to read and originalFileContent is the content of that file. We will read from the file and store it in originalFileContent.

  2. Create one BufferedReader and one BufferedWriter object . We will use them to read and write contents from the file.

  3. Start a ‘try-catch-finally’ loop to do the file operations.

  4. Create one BufferedReader object . We are passing one FileReader object to the constructor that holds the file path.

  5. Read the first line of the file and store it in currentReadingLine String.

  6. We will keep reading from the file and store it in the currentReadingLine variable. And then we will append it to the main variable originalFileContent . The while loop will run till the reading of the file complets.

  7. Now, we have all the contents of the file in originalFileContent variable. Using replaceAll method, we replaced all ‘new’ words with ‘old’ and save it in modifiedFileContent variable.

  8. Next, using BufferedWriter , open the same file.

  9. Write the modified strings to the file.

  10. Finally, close the BufferedReader and BufferedWriter objects.

Sample Output :

Suppose the input file contains the following lines :

This is a new ball.
This is a new house.
This is a new pen.
All new members are invited to the club.

We are storing it in a file ‘sample.txt’ inside ‘C’ drive. Now, if the above program runs, it will modify the file as below :

This is a old ball.
This is a old house.
This is a old pen.
All old members are invited to the club.

Similar tutorials :