Java replace specific string in text file

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

Leave a Comment