Question: Java Chapter 12 **12.11 ( Remove text ) Write a program that removes all the occurrences of a specified string from a text file. For

Java Chapter 12 **12.11 (Remove text) Write a program that removes all the occurrences of a specified string from a text file. For example, invoking java Exercise12_11 John filename removes the string John from the specified file. Your program should get the arguments from the command line

This is my code

RemoveText.java:

import java.io.*; import java.util.*;

public class RemoveText { // main method. public static void main(String[] args) { // Checking for invalid command line entry. if (args.length != 2) { System.out.println("Usage: java RemoveText "); System.exit(0); }

File sourceFile = new File(args[1]); // Checking the existence of the file. if (!sourceFile.exists()) { System.out .println("Source file does not exist. Program will exit. "); System.exit(0); } File tempFile = new File("temp_" + args[1]);

// Creating the Scanner object. Scanner input = null; try { input = new Scanner(sourceFile); } catch (FileNotFoundException e) { // this will never be executed as we have already checked that file exists }

// Creating the PrintWriter object. PrintWriter output = null; try { output = new PrintWriter(tempFile); } catch (FileNotFoundException e) { // if file doesn't exist it creates the file e.printStackTrace(); } while (input.hasNext()) { String s1 = input.nextLine(); // Removing the text. String s2 = s1.replaceAll(args[0], ""); output.println(s2); } input.close(); // Closing the stream. output.close(); // Closing the stream. sourceFile.delete(); // Deleting the original file. tempFile.renameTo(sourceFile); // Renaming the temp file. tempFile.delete(); // Deleting the temp file. } }

input file: input Hi My Name is Jaydan. Jaydan is writing a code for question 12.11 (Remove text) Jaydan feels good about it. Now to run the executable, enter the commands in format: java RemoveText but is just does not remove Jaydan

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!