java替换textfile中的特定字符串

Pin*_*ndo 3 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
Run Code Online (Sandbox Code Playgroud)

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

我想要做的是读取文件然后用另一个值替换给定行中的字符串的一部分(例如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
                            }
                        }
                    }
Run Code Online (Sandbox Code Playgroud)

小智 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();
}
Run Code Online (Sandbox Code Playgroud)

  • 必须将整个文件读入内存。如果文件太大可能会出现问题。 (3认同)
  • 解决方案可删除换行符(如果有) (2认同)