KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > StringReplace


1 /**
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util;
5
6 import java.io.*;
7 import com.tc.util.StringUtil;
8
9 /**
10  * A small app that does a simple substring search and replace. It takes its input from the stdin and sends the result to stdout.
11  * The strings to search and replaced for is passed as a parameter.
12  *
13  * Sets the exit code to 1 if any error occurs, otherwise the exit code is set to 0.
14  */

15 public final class StringReplace
16   extends Thread JavaDoc {
17
18   private PrintStream ps = null;
19   private DataInputStream dis = null;
20   private String JavaDoc search = null;
21   private String JavaDoc replace = null;
22
23   /**
24    */

25   private StringReplace(PrintStream ps, DataInputStream dis, String JavaDoc search, String JavaDoc replace) {
26     this.ps = ps;
27     this.dis = dis;
28     this.search = search;
29     this.replace = replace;
30   }
31  
32   /**
33    */

34   public void run() {
35     if (ps != null && dis != null) {
36       try {
37         String JavaDoc source = null;
38         while ((source = dis.readLine()) != null) {
39           ps.println(StringUtil.replaceAll(source, search, replace, false));
40           ps.flush();
41         }
42         ps.close();
43       } catch (IOException e) {
44         System.err.println(e.getMessage());
45         System.err.println(e.getStackTrace());
46         System.exit(1);
47       }
48     }
49   }
50
51   /**
52    */

53   protected void finalize() {
54     try {
55       if (ps != null) {
56         ps.close();
57         ps = null;
58       }
59       if (dis != null) {
60         dis.close();
61         dis = null;
62       }
63     } catch (IOException e) {
64       System.err.println(e.getMessage());
65       System.err.println(e.getStackTrace());
66       System.exit(1);
67     }
68   }
69    
70   /**
71    */

72   public static void main(String JavaDoc[] args) {
73     String JavaDoc search = args.length >= 1 ? args[0] : "";
74     String JavaDoc replace = args.length >= 2 ? args[1] : "";
75
76     try {
77       (new StringReplace(System.out, new DataInputStream(System.in), search, replace)).start();
78     } catch (Exception JavaDoc e) {
79       System.err.println(e.getMessage());
80       System.err.println(e.getStackTrace());
81       System.exit(1);
82     }
83   }
84 }
85
Popular Tags