In Java, you can replace a string in a text file by reading the file content, replacing the required text with String.replace(), and writing the updated content back to the file. This tutorial shows the existing Apache Commons IO approach and a standard Java NIO approach using Files.readString() and Files.writeString().
Replace a String in a Text File in Java
Replacing text in a file generally involves three operations:
- Read the text from the file.
- Replace the target string in the text.
- Write the modified text back to the file.
For literal text replacement, Java’s String.replace() method is suitable. It replaces every occurrence of the specified character sequence in the string and returns a new string containing the replacements.
The original String is not modified because Java strings are immutable. Therefore, assign the value returned by replace() to a variable before writing it back to the file.
String updatedText = text.replace("old text", "new text");
Replace a String in File Using Apache Commons IO
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.
The call to data.replace("user", "reader") replaces both occurrences of user. The resulting string is then written back to myfile.txt, replacing the previous file content.
Replace Text in a File Using Java Files.readString() and Files.writeString()
If you do not need Apache Commons IO, modern Java provides file-reading and file-writing methods in the java.nio.file.Files class. For a text file that can reasonably be held in memory, you can read the complete file, perform the replacement, and write the result back.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class Example {
public static void main(String[] args) {
Path file = Path.of("myfile.txt");
try {
String data = Files.readString(file, StandardCharsets.UTF_8);
String updatedData = data.replace("user", "reader");
Files.writeString(file, updatedData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here, Files.readString() reads the contents of myfile.txt into a string. replace() creates the updated string, and Files.writeString() writes that string back to the same path.
The example explicitly uses UTF-8 so that the same character encoding is used when reading and writing the file.
How String.replace() Changes File Content
String.replace() performs a literal replacement. The first argument is the text to find, and the second argument is the replacement text.
text.replace(target, replacement)
For example:
String text = "red car, red bus";
String result = text.replace("red", "blue");
System.out.println(result);
blue car, blue bus
The method replaces all literal occurrences of red. The same behavior applies when the string being processed contains text read from a file.
String.replace() vs replaceAll() for File Replacement
replace() and replaceAll() are not interchangeable when the search text contains characters that have special meaning in regular expressions.
replace()treats the target as literal text.replaceAll()treats its first argument as a regular expression.
If the requirement is simply to replace an exact word or phrase in a file, replace() is usually the clearer choice. Use replaceAll() when the text to match is intentionally described by a regular-expression pattern.
String data = "Item 123, Item 456";
String updated = data.replaceAll("\\d+", "NUMBER");
System.out.println(updated);
Item NUMBER, Item NUMBER
Replace Only the First Matching String in File Content
String.replace() replaces every matching occurrence. If you need to replace only the first occurrence, replaceFirst() can be used, but its search argument is a regular expression.
String data = "user logged in; user opened a file";
String updated = data.replaceFirst("user", "reader");
System.out.println(updated);
reader logged in; user opened a file
If the text being searched for comes from a user or another external source and should be treated literally, remember that replaceFirst() uses regular-expression syntax rather than plain literal matching.
Replace Multiple Different Strings in a Java File
For a small, known set of replacements, you can apply replace() more than once before writing the final string back to the file.
String updatedData = data
.replace("user", "reader")
.replace("Tutorials", "Guides")
.replace("Hello", "Welcome");
The replacements are applied in order. This matters when the replacement produced by one operation can also match the target of a later operation.
Case-Sensitive String Replacement in Java Files
String.replace() is case-sensitive. For example, replacing "user" does not replace "User" or "USER".
String text = "user User USER";
String result = text.replace("user", "reader");
System.out.println(result);
reader User USER
If the file requires case-insensitive matching, use a carefully constructed regular expression or another matching strategy rather than assuming that replace() ignores case.
Replacing Text Without Overwriting the Original File
The earlier examples write the modified text back to the same file. If the original content must be preserved, write the updated string to a different path instead.
Path inputFile = Path.of("myfile.txt");
Path outputFile = Path.of("myfile-updated.txt");
String data = Files.readString(inputFile, StandardCharsets.UTF_8);
String updatedData = data.replace("user", "reader");
Files.writeString(outputFile, updatedData, StandardCharsets.UTF_8);
This leaves myfile.txt unchanged and creates or updates myfile-updated.txt with the replacement text.
Consider File Size Before Reading the Entire File into a String
The examples on this page read the complete file into memory. That keeps the code simple and works well for ordinary small text files, but it may not be appropriate for very large files.
For a large file, consider processing the content incrementally, such as reading line by line and writing the modified text to a separate output file. This avoids keeping the entire file contents in one String.
Checks Before Replacing a String in a Java File
- Confirm that the input path points to the intended text file.
- Use the same appropriate character encoding when reading and writing the file.
- Use
replace()for literal text andreplaceAll()only when regular-expression matching is required. - Remember that
replace()is case-sensitive and replaces all matching occurrences. - Assign the returned replacement string because
Stringobjects are immutable. - Write to a separate output file when the original file must be preserved.
- Handle
IOExceptionwhen performing file operations. - For very large files, prefer incremental processing rather than loading the complete file into memory.
Java File String Replacement Summary
To replace a string in a text file in Java, read the file content, call String.replace() with the target and replacement strings, and write the returned string to the required file. Apache Commons IO can perform the file operations as shown in the original example, while standard Java provides Files.readString() and Files.writeString() for the same read-modify-write pattern.
In this Java Tutorial, we learned how to replace a string in file with another string.
TutorialKart.com