I just found Apache POI library very useful for editing Word files using Java. Specifically, I want to edit a DOCX file using Apache POI\'s XWPF classes. I
The answer accepted here needs one more update along with Justin Skiles update.
r.setText(text, 0);
Reason: If not updating setText with pos variable, the output will be the combination of old string and replace string.