source: greenstone3/trunk/src/java/org/greenstone/anttasks/RegexSearchReplace.java@ 14604

Last change on this file since 14604 was 14604, checked in by oranfry, 17 years ago

brought important changes across from 3.03 branch, mostly version number stuff. namely r14565:14566, r14569:14570, r14573:14576, r14579:14580

File size: 2.2 KB
Line 
1package org.greenstone.anttasks;
2
3import org.apache.tools.ant.*;
4import org.apache.tools.ant.taskdefs.*;
5import java.util.*;
6import java.io.*;
7import java.util.regex.*;
8
9
10public class RegexSearchReplace extends Task {
11 private File file = null;
12 private String pattern = null;
13 private String replacement = null;
14
15
16 /**
17 * for testing
18 */
19 public static void main( String[] args ) {
20 RegexSearchReplace rsr = new RegexSearchReplace();
21 rsr.setFile(new File (args[0]));
22 rsr.setPattern(args[1]);
23 rsr.setReplacement(args[2]);
24
25 rsr.execute();
26
27 }
28
29 public void execute() {
30
31 if ( file == null ) {
32 throw new BuildException( "Error - No file specified !!" );
33 }
34
35 if ( pattern == null ) {
36 throw new BuildException( "Error - No pattern specified !!" );
37 }
38
39 if (replacement == null) {
40 replacement = "";
41 }
42
43
44 //create the output stream
45 BufferedWriter out = null;
46 File temp = null;
47 try {
48 // Create temp file.
49 temp = File.createTempFile("rsr", ".tmp");
50
51 // Delete temp file when program exits.
52 temp.deleteOnExit();
53
54 // Write to temp file
55 out = new BufferedWriter(new FileWriter(temp));
56
57 } catch (IOException e) {}
58
59
60 //create the input stream
61 BufferedReader in = null;
62 try {
63 in = new BufferedReader(new FileReader( file ));
64 } catch ( Exception e ) {}
65
66 //pass the file through, searching and replacing
67 String line;
68 try {
69 while ( (line = in.readLine()) != null ) {
70 line = line.replaceAll( pattern, replacement);
71 out.write(line);
72 out.newLine();
73 }
74 //close them both up
75 in.close();
76 out.close();
77
78 } catch ( Exception e ) {
79 e.printStackTrace();
80 }
81
82
83
84 //copy the new file (temp) over the original
85 try {
86 InputStream i = new FileInputStream(temp);
87 OutputStream o = new FileOutputStream(file);
88
89 // Transfer bytes from in to out
90 byte[] buf = new byte[1024];
91 int len;
92 while ((len = i.read(buf)) > 0) {
93 o.write(buf, 0, len);
94 }
95
96 //close them up
97 i.close();
98 o.close();
99 } catch ( Exception e ) {}
100
101 }
102
103
104 public void setFile(File file) {
105 this.file = file;
106 }
107
108 public void setPattern(String pattern) {
109 this.pattern = pattern;
110 }
111
112 public void setReplacement(String replacement) {
113 this.replacement = replacement;
114 }
115
116
117}
Note: See TracBrowser for help on using the repository browser.