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:
| 1 2 3 4 5 |
|
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.
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
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.
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
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.
| 1 2 3 4 5 |
|
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 |
|
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.
Download
You can download the full source code of this example here: java replace specific word file

395

被折叠的 条评论
为什么被折叠?



