java replace specific string in textfile

后端 未结 3 1758
渐次进展
渐次进展 2020-11-30 14:55

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         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 15:07

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

提交回复
热议问题