import org.apache.tools.ant.*; import org.apache.tools.ant.taskdefs.*; import java.util.*; import java.io.*; import java.util.regex.*; public class RegexSearchReplace extends Task { private File file = null; private String pattern = null; private String replacement = null; /** * for testing */ public static void main( String[] args ) { RegexSearchReplace rsr = new RegexSearchReplace(); rsr.setFile(new File (args[0])); rsr.setPattern(args[1]); rsr.setReplacement(args[2]); rsr.execute(); } public void execute() { if ( file == null ) { throw new BuildException( "Error - No file specified !!" ); } if ( pattern == null ) { throw new BuildException( "Error - No pattern specified !!" ); } if (replacement == null) { replacement = ""; } //create the output stream BufferedWriter out = null; File temp = null; try { // Create temp file. temp = File.createTempFile("rsr", ".tmp"); // Delete temp file when program exits. temp.deleteOnExit(); // Write to temp file out = new BufferedWriter(new FileWriter(temp)); } catch (IOException e) {} //create the input stream BufferedReader in = null; try { in = new BufferedReader(new FileReader( file )); } catch ( Exception e ) {} //pass the file through, searching and replacing String line; try { while ( (line = in.readLine()) != null ) { line = line.replaceAll( pattern, replacement); out.write(line); out.newLine(); } //close them both up in.close(); out.close(); } catch ( Exception e ) { e.printStackTrace(); } //copy the new file (temp) over the original try { InputStream i = new FileInputStream(temp); OutputStream o = new FileOutputStream(file); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = i.read(buf)) > 0) { o.write(buf, 0, len); } //close them up i.close(); o.close(); } catch ( Exception e ) {} } public void setFile(File file) { this.file = file; } public void setPattern(String pattern) { this.pattern = pattern; } public void setReplacement(String replacement) { this.replacement = replacement.replaceAll( "\\", "\\\\" ); } }