import java.io.*; // for File and PrintWriter import java.util.*; // for Scanner public class Ch14_11 // read each String of an input file and send it to an output file unless the String matches the word input by the user to be removed { // note: as we are only fetching Strings that are delimited by blanks, we have to insert blanks after each word of the output file // and since the delimiter will include punctuation as "end of a string", we are looking for the word or the substring of the word without // looking at the last character (e.g., if we are looking to remove "dog", we would also remove "dog.", "dogs" and "dog!" public static void main(String[] args) { File f=null, f2=null; // need to initialize s and p up here because of the finally clause. Java compiler complains if these are not initialized so I set them to null Scanner s=null, s2=null; // don't want to set them to new... in case they throw an exception, we have to try to open the files within the try block to PrintWriter p=null; // catch any problem String word; // the word that the user wants to delete from the file try{ f=new File("input.txt"); // obtain as a File both the input and the output files as f and f2 f2=new File("output.txt"); s=new Scanner(f); // s is the Scanner used to control access to the input file s2=new Scanner(System.in); System.out.println("What word do you want removed from the file?"); // get the word to remove from the file from the user word=s2.next(); p=new PrintWriter(f2); // open the output file as p scanAndRemove(s, word, p); // all of the removal action takes place in scanAndRemove } catch(IOException e) // I/O error? Catch it here { System.out.println(e); } finally // whether an Exception arises or not, when done close both s and p { s.close(); p.close(); } } // this method will iterate through the file controlled by s, obtaining each String and comparing it to w, if the next String temp and w are the same or if temp minus the last character and w // are the same, do not output it to p, otherwise output temp to p public static void scanAndRemove(Scanner s, String w, PrintWriter p) { String temp; while(s.hasNext()) // does the file have more to it? If so, continue { temp=s.next(); // get the next String from the file, Strings are delimited by spaces (since we did not override the default) if(!temp.equals(w)&&!temp.substring(0,temp.length()-1).equals(w)) p.print(temp+" "); } } }