Java replace specific string in text file
65,556
Solution 1
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.
Solution 2
You could create a string of total file content and replace all the occurrence in the string and write to that file again.
You could something like this:
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();
}
Author by
Pindo
Updated on July 28, 2021Comments
-
Pindo almost 3 years
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 to read the file and 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 } } }
-
Pindo about 10 yearsonce it is replaced how to i write it back to the same file?
-
Jason about 10 yearsYou shouldn't write back into the same file while you are reading it. You could write a new file, and then at the end of the process delete the file you read and rename the new one.
-
drakonli over 6 yearsSolution removes line breaks if there are any
-
Paulo Pereira over 5 yearsThe entire file must be read to memory. Can be a problem if the file is too big.