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

时间:2014-05-05 06:29:33

标签: java file-io text-files

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

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

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

我想要做的是读取文件然后用另一个值替换给定行中的字符串的一部分(例如textFiles / a.txt)(例如/某事物/ 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
                            }
                        }
                    }

4 个答案:

答案 0 :(得分:9)

您可以创建一个包含总文件内容的字符串,并替换字符串中的所有匹配项并再次写入该文件。

你可以这样:

File log= new File("log.txt");
String search = "textFiles/a.txt";
String replace = "replaceText/b.txt";

try{
    FileReader fr = new FileReader(log);
    String s;
    String totalStr = "";
    try (BufferedReader br = new BufferedReader(fr)) {

        while ((s = br.readLine()) != null) {
            totalStr += s;
        }
        totalStr = totalStr.replaceAll(search, replace);
        FileWriter fw = new FileWriter(log);
    fw.write(totalStr);
    fw.close();
    }
}catch(Exception e){
    e.printStackTrace();
}

答案 1 :(得分:2)

一种方法是使用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()来查找搜索字符串在一行中的位置。

答案 2 :(得分:0)

Java 文件和流的解决方案

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

private static void replaceAll(String filePath, String text, String replacement) {
        
        Path path = Paths.get(filePath);
        // Get all the lines
        try (Stream<String> stream = Files.lines(file, StandardCharsets.UTF_8)) {
            // Do the replace operation
            List<String> list = stream.map(line -> line.replace(text, replacement)).collect(Collectors.toList());
            // Write the content back
            Files.write(file, list, StandardCharsets.UTF_8);
        } catch (IOException e) {
            LOG.error("IOException for : " + file, e);
            e.printStackTrace();
        }
    }

用法

replaceAll("test.txt", "original text", "new text");

答案 3 :(得分:-1)

一个非常简单的解决方案是使用:

s = s.replace( "textFiles/a.txt", "something/bob.txt" );

要替换所有匹配项,请使用另一个提案中显示的replaceAll,其中使用了正则表达式 - 请注意转义所有魔术字符,如此处所示。

相关问题