I am trying to replace only matched strings in a file by using matcher.replaceAll().Like below
public static void main(String[] args) throws IOException, BadLocationException {
FileInputStream fis = null;
String output = new Scanner(new File("C:/file.in")).useDelimiter("\\Z").next();//file.in contains HTML text
String s2 = null;
StringWriter writer = new StringWriter();
for (int i=0; i<patternList.size(); i++)//PatternList contains names to be extracted from file
{
Matcher matcher = patternList.get(i).matcher(output);
while (matcher.find())
{
String matched = matcher.group();//I need to replace only matched strings returned by matcher
s2=matcher.replaceAll("<span style='background-color:red;'>"+matched+"</span>");
File file = new File("C:/data/filename.in");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(s2);
bw.close();
}
}
The resulting string s2 updated with only last string in PatternList.Each time i am overwriting the string with newly matched string. How can i get the final big string which is updated with all matched strings(names in patternlist).