【问题标题】:Java replace specific string in text fileJava替换文本文件中的特定字符串
【发布时间】:2014-06-21 09:12:01
【问题描述】:

我有一个名为 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)替换为另一个值(例如 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
                            }
                        }
                    }

【问题讨论】:

  • 如果你愿意使用 perl:perlpie.com
  • 如果您存储字符串的格式对于所有实例都相同,您可以做的是:- 搜索该特定字符串,使用分隔符创建一个字符串数组,在您的情况下,在该数组中的特定索引处替换您的字符串,然后在您的文本文件中替换回。这是一种方式。效率不高,但可以解决您的目的
  • 试试s = s.replaceAll("(?<=\\d{4}\\,)(.*)(?=\\,images)", "something/bob.txt");

标签: java file-io text-files


【解决方案1】:

一种方法是使用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】:

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

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

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

【讨论】:

    【解决方案3】:

    您可以创建一个包含文件总内容的字符串,然后替换字符串中出现的所有内容,然后再次写入该文件。

    你可以这样:

    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();
    }
    

    【讨论】:

    • 解决方案如果有换行符就去掉
    • 必须将整个文件读入内存。如果文件太大,可能会出现问题。
    【解决方案4】:

    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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-14
      • 2011-06-30
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多