Java – Replace a String in File

You can replace a string in file with another string in Java.

In the following examples, we present you different ways to replace a string in text file with a new string.

The basic idea is that, we shall read the content of the text file, replace the string with new string in the content of file, and then write this new content back to the text file.

Example 1 – Replace String in Text file

For this example, we shall use the library org.apache.commons.io. The jar file we are including in the build path is commons-io-2.4.jar.

Consider the following text file.

myfile.txt

Hello user! Welcome to www.tutorialkart.com.
Hi user! Welcome to Java Tutorials.

In this example, we shall replace the string “user” with new string “reader” in the above text file myfile.txt.

Example.java

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class Example {
	/**
	 * An example program to replace a string in text file
	 */
	public static void main(String[] args) {
		File textFile = new File("myfile.txt");
		try {
			String data = FileUtils.readFileToString(textFile);
			data = data.replace("user", "reader");
			FileUtils.writeStringToFile(textFile, data);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Run the above program. Open the text file myfile.txt and you should see that the string “user” is no more and has been replaced with the string “reader”.

Output

Hello reader! Welcome to www.tutorialkart.com.
Hi reader! Welcome to Java Tutorials.

Conclusion

In this Java Tutorial, we learned how to replace a string in file with another string.