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.niojava.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

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.

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

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.

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

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.

1

2

3

4

5

<dependency>

    <groupId>commons-io</groupId>

    <artifactId>commons-io</artifactId>

    <version>2.19.0</version>

</dependency>

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

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 BufferedReaderBufferedWriter, 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值