1 import java.io.*;
2 import java.util.*;
3
4 public class ReplaceText {
5 public static void main(String[] args) throws Exception {
6
7 if (args.length != 4) {
8 System.out.println(
9 "Usage: java ReplaceText sourceFile targetFile oldStr newStr");
10 System.exit(1);
11 }
12
13
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
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
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 }