Problem

(Replace text) Listing 1, ReplaceText.java, gives a program that replaces text in a source...

(Replace text) Listing 1, ReplaceText.java, gives a program that replaces text in a source file and saves the change into a new file. Revise the program to save the change into the original file. For example, invoking

java Exercise12_16 file oldString newString

replaces oldString in the source file with newString.

LISTING 1 ReplaceText.java

1 import java.io.*;

2 import java.util.*;

3

4 public class ReplaceText {

5 public static void main(String[] args) throws Exception {

6 // Check command line parameter usage

7 if (args.length != 4) {

8 System.out.println(

9 "Usage: java ReplaceText sourceFile targetFile oldStr newStr");

10 System.exit(1);

11 }

12

13 // Check if source file exists

14 File sourceFile = new File(args[0]);

15 if (!sourceFile.exists()) {

16 System.out.println("Source file " + args[0] + " does not exist");

17 System.exit(2);

18 }

19

20 // Check if target file exists

21 File targetFile = new File(args[1]);

22 if (targetFile.exists()) {

23 System.out.println("Target file " + args[1] + " already exists");

24 System.exit(3);

25 }

26

27 try (

28 // Create input and output files

29 Scanner input = new Scanner(sourceFile);

30 PrintWriter output = new PrintWriter(targetFile);

31 ) {

32 while (input.hasNext()) {

33 String s1 = input.nextLine();

34 String s2 = s1.replaceAll(args[2], args[3]);

35 output.println(s2);

36 }

37 }

38 }

39 }

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT