Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Practical Azure SQL Database For Modern Developers Building Applications In The Microsoft Cloud

Authors: Davide Mauri, Silvano Coriani, Anna Hoffma, Sanjay Mishra, Jovan Popovic

1st Edition

1484263693, 978-1484263693

More Books

Students also viewed these Databases questions