java替换textfile中的特定字符串

我有一个名为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 } } } 

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

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

你可能会这样:

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

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

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

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