1. Write a program that replaces text in a source file and saves the changes in
ID: 3680179 • Letter: 1
Question
1. Write a program that replaces text in a source file and saves the changes in the same source file.
The program should take the following from user input.
o Source file name
o Old string that will be replaced
o New string that is used to replace the old string
2. Write a program that replaces text in a source file, saves the changes in the same source file, and test the program .
The program should take the following inputs from users.
o Source file name
o Old string that will be replaced
o New string that is used to replace the old string
In java
Explanation / Answer
//Progarm to replace string in a file and save the changes to the same file
import java.io.*;
public class StringReplace
{
public static void main(String args[])
{
try
{
File file = new File("source.txt");
BufferedReader reader = new BufferedReader(new FileReader(source));
String lines = "", oldtext = "";
while((lines = reader.readLine()) != null)
{
oldtext += lines + " ";
}
reader.close();
// Now to replace a word in a file
String newtext = oldtext.replaceAll("Hello", "Thanks");
//Now to replace a line in a file
String newtext = oldtext.replaceAll("Hello Everybody", "Thank You");
FileWriter writer = new FileWriter("source.txt");
writer.write(newtext);writer.close();
}
//Checking for stack overflow
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.