java替换文本文件中的特定字符串 [英] java replace specific string in textfile
问题描述
我有一个名为log.txt的文本文件
它包含以下数据:
$ $ p $ 1 Mon May 05 00:05:45 WST 2014,textFiles / a.txt,images / download.jpg
2,,May 05 05:05:45 WST 2014,textFiles / a.txt,images / download。 jpg
第一个逗号之前的数字是指定每个项目的索引。 b
我想要做的是读取文件,然后用另一个值(例如something / bob.txt)替换给定行中的字符串的一部分(例如textFiles / a.txt)。 >
这是我到目前为止
档案记录=新档案log.txt中);
String search =1,,Mon May 05 00:05:45 WST 2014,textFiles / a.txt,images / download.jpg;
//文件读取
FileReader fr = new FileReader(log);
String s;
try(BufferedReader br = new BufferedReader(fr)){
while((s = br.readLine())!= null ){
if(s.equals(search)){
//不知道该做什么
}
}
}
$一个方法是使用 String.replaceAll()
解决方案 / code>: 文件日志=新文件(log.txt);
字符串搜索=textFiles / a\\.txt; //< - 改为使用String.replaceAll()
字符串替换=something / bob.txt;
//文件读取
FileReader fr = new FileR eader(log);
String s;
尝试{
BufferedReader br = new BufferedReader(fr); ((s = br.readLine())!= null){
s.replaceAll(search,replacement);
//对结果行进行处理
code $ $ $ $ $ $ $ $ $ $ $ $ >您也可以使用正则表达式,或 String.indexOf()
来查找您的搜索字符串出现的位置。
I've got a text file called log.txt
It's got the following data
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
the numbers before the first comma are indexes that specify each item.
what I want to do is read the file then replace one part of the string(e.g. textFiles/a.txt) in a given line with another value(e.g. something/bob.txt).
this is what i have so far
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
}
}
}
解决方案 One approach would be to use 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
}
}
You could also use regular expressions, or String.indexOf()
to find where in a line your search string appears.
这篇关于java替换文本文件中的特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文