Pindo Pindo - 1 month ago 11
Java Question

java replace specific string in textfile

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
}
}
}

Answer

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.