source: release-kits/shared/ant-tasks/orans/RegexSearchReplace.java@ 15065

Last change on this file since 15065 was 15065, checked in by oranfry, 16 years ago

made the rsr task windows-filename-safe

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