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

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

made the rsr task windows filename safe - for real this time

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