package examples; import java.io.*; /** * Replace is a utility for replacing all occurrences of one string by another in a file. * @author kjg * */ public class Replace { /** * REQUIRES: The input file 'in' must exist. The 'in' and 'out' files must not be the same file. * MODIFIES: The output file. * EFFECTS: The input file is copied to the output file, with each occurence of the oldstring * replaced by newstring. * @param oldstring the String to be replaced * @param newstring the replacement String * @param in the input File * @param out the output File * @throws IOException if the input file does not exist or the output file cannot be created. */ public static void replace(String oldstring, String newstring, File in, File out) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(in)); PrintWriter writer = new PrintWriter(new FileWriter(out)); String line = null; while ((line = reader.readLine()) != null) { writer.println(line.replaceAll(oldstring,newstring)); } reader.close(); writer.close(); } /** * Allows use on the command line, as
* java Replace oldstring newstring inputfilename outputfilename * @param args array of the four String arguments provided by the user */ public static void main(String[] args) { try { String oldString = args[0]; String newString = args[1]; File in = new File(args[2]); if (!in.exists()) { System.out.println("The input file " + in + " does not exist."); return; } File out = new File(args[3]); if (out.exists()) { System.out.println("The output file " + out + " already exists."); return; } replace(oldString, newString, in, out); } catch (Exception e) { usage(); } } static void usage() { System.out.println("Usage: Replace "); } }