DEV Community

Cover image for Case Study: Replacing Text
Paul Ngugi
Paul Ngugi

Posted on

Case Study: Replacing Text

Suppose you are to write a program named ReplaceText that replaces all occurrences of a string in a text file with a new string. The file name and strings are passed as command-line arguments as follows:

java ReplaceText sourceFile targetFile oldString newString

For example, invoking

java ReplaceText FormatString.java t.txt StringBuilder StringBuffer

replaces all the occurrences of StringBuilder by StringBuffer in the file FormatString.java and saves the new file in t.txt.

The program below gives the program. The program checks the number of arguments passed to the main method (lines 9–12), checks whether the source and target files exist (lines 15–26), creates a Scanner for the source file (line 30), creates a PrintWriter for the target file (line 31), and repeatedly reads a line from the source file (line 34), replaces the text (line 35), and writes a new line to the target file (line 36).

package demo;
import java.io.*;
import java.util.*;

public class ReplaceText {

    public static void main(String[] args) throws Exception {
        // Check command line parameter usage
        if(args.length != 4) {
            System.out.println("Usage: java ReplaceText sourceFile targetFile oldStr newStr");
            System.exit(1);
        }

        // Check if source file exists
        File sourceFile = new File(args[0]);
        if(!sourceFile.exists()) {
            System.out.println("Source file " + args[0] + " does not exist");
            System.exit(2);
        }

        // Check if target file exists
        File targetFile = new File(args[1]);
        if(targetFile.exists()) {
            System.out.println("Target file " + args[1] + " already exists");
            System.exit(3);
        }

        try (
            // Create input and output files
            Scanner input = new Scanner(sourceFile);
            PrintWriter output = new PrintWriter(targetFile);
        ){
            while(input.hasNext()) {
                String s1 = input.nextLine();
                String s2 = s1.replaceAll(args[2], args[3]);
                output.println(s2);
            }
        }
    }

}

Enter fullscreen mode Exit fullscreen mode

In a normal situation, the program is terminated after a file is copied. The program is terminated abnormally if the command-line arguments are not used properly (lines 9–12), if the source file does not exist (lines 15–19), or if the target file already exists (lines 23–26). The exit status code 1, 2, and 3 are used to indicate these abnormal terminations
(lines 11, 18, 25).

Top comments (0)