我有一个名为 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
第一个逗号前的数字是指定每个项目的索引。
我想做的是读取文件,然后用另一个值(例如 something/bob.txt)替换给定行中字符串的一部分(例如 textFiles/a.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
}
}
}
最佳答案
您可以创建一个包含所有文件内容的字符串并替换字符串中出现的所有内容,然后再次写入该文件。
你可以这样:
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();
}
关于Java替换文本文件中的特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23466179/