01: /**
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */package com.tc.util;
04:
05: import java.io.*;
06: import com.tc.util.StringUtil;
07:
08: /**
09: * A small app that does a simple substring search and replace. It takes its input from the stdin and sends the result to stdout.
10: * The strings to search and replaced for is passed as a parameter.
11: *
12: * Sets the exit code to 1 if any error occurs, otherwise the exit code is set to 0.
13: */
14: public final class StringReplace extends Thread {
15:
16: private PrintStream ps = null;
17: private DataInputStream dis = null;
18: private String search = null;
19: private String replace = null;
20:
21: /**
22: */
23: private StringReplace(PrintStream ps, DataInputStream dis,
24: String search, String replace) {
25: this .ps = ps;
26: this .dis = dis;
27: this .search = search;
28: this .replace = replace;
29: }
30:
31: /**
32: */
33: public void run() {
34: if (ps != null && dis != null) {
35: try {
36: String source = null;
37: while ((source = dis.readLine()) != null) {
38: ps.println(StringUtil.replaceAll(source, search,
39: 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[] args) {
73: String search = args.length >= 1 ? args[0] : "";
74: String replace = args.length >= 2 ? args[1] : "";
75:
76: try {
77: (new StringReplace(System.out, new DataInputStream(
78: System.in), search, replace)).start();
79: } catch (Exception e) {
80: System.err.println(e.getMessage());
81: System.err.println(e.getStackTrace());
82: System.exit(1);
83: }
84: }
85: }
|