Text replacer Learn programming Java

Lesson:

File Management


Exercise:

Text replacer 18


Objetive:

Create a program to replace words in a text file, saving the result into a new file.

The file, the word to search and word to replace it with must be given as parameters:

replace file.txt hello goodbye

The new file would be named "file.txt.out" and contain all the appearances of "hello" replaced by "goodbye".


Code:

package Replace;
public class Main
{
	public static void main(String[] args)
	{
		ReplaceTextFile("file.txt", "Hola", "hola");
	}

	public static void ReplaceTextFile(String urlFile, String textReplace, String newText)
	{
		java.io.FileReader myfileRd = new java.io.FileReader(urlFile);
	    java.io.BufferedReader myfileRdBufferedReader = new java.io.BufferedReader(myfileRd);
		java.io.FileWriter myfileWr = new java.io.FileWriter("file.txt.out");
		String line = " ";

		do
		{
			line = myfileRdBufferedReader.readLine();
			if (line != null)
			{
				line = line.replace(textReplace, newText);
				myfileWr.write(line + System.lineSeparator());
			}
		} while (line != null);
		myfileWr.close();
		myfileRd.close();
	}
}