Java替换文本文件中的特定字符串

Java替换文本文件中的特定字符串

本文介绍了Java替换文本文件中的特定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 log.txt 的文本文件.它有以下数据

I've got a text file called log.txt.It's got the following data

1,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg
2,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg

第一个逗号之前的数字是指定每个项目的索引.

The numbers before the first comma are indexes that specify each item.

我想要做的是读取文件,然后用另一个值(例如 something/bob.txt)替换给定行中字符串的一部分(例如 textFiles/a.txt).

What I want to do is to read the file and then replace one part of the string(e.g. textFiles/a.txt) in a given line with another value(e.g. something/bob.txt).

这是我目前所拥有的:

    File log= new File("log.txt");
                    String search = "1,,Mon May 05 00:05:45 WST 2014,textFiles/a.txt,images/download.jpg;
                    //file reading
                    FileReader fr = new FileReader(log);
                    String s;
                    try (BufferedReader br = new BufferedReader(fr)) {

                        while ((s = br.readLine()) != null) {
                            if (s.equals(search)) {
                                //not sure what to do here
                            }
                        }
                    }

推荐答案

一种方法是使用 String.replaceAll():

File log= new File("log.txt");
String search = "textFiles/a\\.txt";  // <- changed to work with String.replaceAll()
String replacement = "something/bob.txt";
//file reading
FileReader fr = new FileReader(log);
String s;
try {
    BufferedReader br = new BufferedReader(fr);

    while ((s = br.readLine()) != null) {
        s.replaceAll(search, replacement);
        // do something with the resulting line
    }
}

您还可以使用正则表达式或 String.indexOf() 来查找搜索字符串在一行中出现的位置.

You could also use regular expressions, or String.indexOf() to find where in a line your search string appears.

这篇关于Java替换文本文件中的特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:33