How to Replace a Specific Word in a File Using Java
In this article, we explore several approaches to replacing a specific word within a text file using Java, including standard libraries (java.nio, java.io) and the Apache Commons IO library.
1. Example Input File
let’s assume we have a file called sample.txt with the following content:
Hello world. The world is not enough. Welcome to the world of Java! Explore the new world beyond imagination. Goodbye world.
Our goal is to replace all occurrences of the word "world" with "universe".
2. Using java.nio.file.Files
This is the most modern way of reading and writing files in Java using the Files utility class in the java.nio.file package.
public class ReplaceWordNio {
public static void main(String[] args) {
Path filePath = Path.of("src/main/resources/sample.txt");
String targetWord = "world";
String replacement = "universe";
try {
List<String> lines = Files.readAllLines(filePath);
List<String> updatedLines = lines.stream()
.map(line -> line.replace(targetWord, replacement))
.collect(Collectors.toList());
Files.write(filePath, updatedLines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
System.out.println("Word replaced successfully in file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
The method Files.readAllLines(filePath) reads all lines of the file into memory, which is suitable for small to moderately sized text files. A Stream is then used to map each line, replacing the target word as needed. Finally, Files.write(...) writes the updated content back to the file, truncating the existing content to ensure it is fully overwritten.
3. Using BufferedReader and BufferedWriter
For memory efficiency, we can use classic java.io classes like BufferedReader and BufferedWriter.
public class ReplaceWordBuffered {
public static void main(String[] args) {
Path inputFile = Path.of("src/main/resources/sample.txt");
Path tempFile = Path.of("src/main/resources/temp.txt");
String targetWord = "world";
String replacement = "universe";
try (BufferedReader reader = Files.newBufferedReader(inputFile);
BufferedWriter writer = Files.newBufferedWriter(tempFile)) {
String currentLine;
while ((currentLine = reader.readLine()) != null) {
String updatedLine = currentLine.replace(targetWord, replacement);
writer.write(updatedLine);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
// Replace original file with the updated one
try {
Files.delete(inputFile);
Files.move(tempFile, inputFile);
System.out.println("Word replaced successfully using BufferedReader and NIO file operations.");
} catch (IOException e) {
System.err.println("Error replacing original file: " + e.getMessage());
}
}
}
This code reads a text file line by line using BufferedReader, replaces occurrences of the word and writes the modified lines to a temporary file using BufferedWriter. After processing, it deletes the original file and renames the temporary file to the original name using Files.delete() and Files.move(), ensuring the file is safely updated.
4. Using Apache Commons IO
Apache Commons IO simplifies file reading and writing significantly with utility methods.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.19.0</version>
</dependency>
public class ReplaceWordCommonsIO {
public static void main(String[] args) {
File file = new File("src/main/resources/sample.txt");
String targetWord = "world";
String replacement = "universe";
try {
String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
content = content.replace(targetWord, replacement);
FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8);
System.out.println("Word replaced successfully using Apache Commons IO.");
} catch (IOException e) {
System.err.println("Error replacing original file: " + e.getMessage());
}
}
}
This approach reads the entire file into a single String using FileUtils.readFileToString, performs the word replacement with String.replace(...), and writes the updated content back using FileUtils.writeStringToFile(...).
5. Conclusion
In this article, we explored multiple ways to replace a specific word in a file using Java. We demonstrated approaches using core Java classes like BufferedReader, BufferedWriter, and Files, as well as the more concise Apache Commons IO library.
6. Download the Source Code
This article covered how to replace a specific word in a file using Java.
You can download the full source code of this example here: java replace specific word file

