How to Replace a String in File in Java?

In this Java tutorial, you will learn how to replace a string in a text file with a new replacement string using String.replace() method, with examples.

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

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

</>

Copy

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值