Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads a text file, removes all occurrences of a specified S

ID: 3804399 • Letter: W

Question

Write a program that reads a text file, removes all occurrences of a specified String and stores the remaining words in another text file. You may assume that the text file contains Strings, one on each line. For example, suppose the input text file lang. txt contains the following words: Java C C++ COBOL Ada Pascal LISP PERL Python Pascal A sample screen dialog is given below: Enter the name of the file to read from: lang.txt Enter the String to remove: Pascal Enter the name of the file to write into: langl.txt Data written into langl.txt Now langl. txt will contain the following: Java C C++ COBOL Ada LISP PERL Python

Explanation / Answer

package com.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;

public class RemoveWordFromFile {

   public static void main(String[] args) throws IOException {
       String str, str1, str2 = null;
       String[] s = null;
       String s1;
       FileReader freader;
       FileWriter fwriter;

       // Reading from console
       BufferedReader br = null;
       Reader r = new InputStreamReader(System.in);
       br = new BufferedReader(r);

       System.out.println("Enter the name of the file to read from.");
       str = br.readLine();
       System.out.println("Enter the String to remove");
       str1 = br.readLine();
       System.out.println("Enter the name of the file to write into.");
       str2 = br.readLine();

       // Reading from a file
       freader = new FileReader(str);

       // writing into a file

       fwriter = new FileWriter(str2);

       LineNumberReader lnReader = new LineNumberReader(freader);
       System.out.println(lnReader);

       while ((s1 = lnReader.readLine()) != null) {
           String finalSentence = "";
           if (s1.contains(str1)) {

               s = s1.split(" ");

               for (int i = 0; i < s.length; i++) {
                   if (str1.equals(s[i])) {
                       continue;
                   } else {
                       finalSentence += s[i] + " ";
                      
                   }
                   fwriter.write(finalSentence + " ");
               }
              
           }
          
           else{
               fwriter.write(s1 + " ");
           }
          
       }
       fwriter.close();
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote