import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import javax.swing.JFileChooser; class ProfanityChecker{ //to store badwords List badWords; //constructor will read the badwors file and add to //badwords list public ProfanityChecker(String s) { FileReader f; try { f = new FileReader(s); BufferedReader bw=new BufferedReader(f); badWords=new ArrayList(); String str; while((str=bw.readLine())!=null){ badWords.add(str); } bw.close(); } catch (FileNotFoundException e) { System.out.println("bad words file not found error"); }catch(IOException e){ } } //run method to run the program void run(){ BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); //loop will continue until user exits while(true){ System.out.println("1.Enter a sentence for profanity check "); System.out.println("2.Choose a file for profanity check "); System.out.println("3.exit"); int option; try { option = Integer.parseInt(bf.readLine()); if(option==1){ //reading from user input and replace the badwords System.out.println("Enter text : "); String words=bf.readLine(); for(String badWord:badWords){ words=words.replaceAll(badWord, "***"); } System.out.println(words); }else if(option==2){ //choosing the text file JFileChooser j=new JFileChooser(); while(true){ //this loop will continue until user selects text file or cancel int r=j.showOpenDialog(null); File f=null; if(r==JFileChooser.APPROVE_OPTION){ f= j.getSelectedFile(); if(!f.getName().endsWith("txt")){ System.out.println("invalid file try choose again"); continue; } BufferedReader bw=new BufferedReader(new FileReader(f)); String line; String newContent=""; while((line=bw.readLine())!=null){ newContent+=line+System.lineSeparator(); } for(String badWord:badWords){ newContent=newContent.replaceAll(badWord, "***"); } FileWriter fw=new FileWriter(f); fw.write(newContent); fw.close(); bw.close(); }else{ break; } if(f!=null) break; }System.out.println("File modified"); }else if(option == 3 ){ //terminate the program System.out.println("Good bye"); System.exit(0); } else{ throw new NumberFormatException(); } } catch (NumberFormatException e) { System.out.println("Invalid input"); } catch (IOException e) { System.out.println("File not found"); } } } }