I am using Apache POI 3.13 and was trying to search and replace texts from a given template file then saving a new generated .docx. Here's my code:
public static void main(String[] args) throws InvalidFormatException, IOException {
String filePath = "Sample.docx";
File outputfile = new File("SampleProcessed.docx");
XWPFDocument doc = new XWPFDocument(OPCPackage.open(filePath));
for (XWPFParagraph p : doc.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains("$VAR")) {
text = text.replace("$VAR", "JohnDoe");
r.setText(text, 0);
}
}
}
}
doc.write(new FileOutputStream(outputfile));
doc.close();
System.out.println("Done");
Desktop.getDesktop().open(outputfile);
}
This looks pretty straightforward but when I run this code, the document "Sample.docx" also get replaced. In the end I am having two documents with identical contents.
Is this the normal behavior of POI? I thought opening the document only loads it into memory, then doing the 'doc.write(OutputStream);' would flush it to disk.
I tried writing to the same 'filePath' but as expected it throws an exception since I'm trying to write to a currently open file.
The only thing that worked was when I copied the template file first and used that copy instead. But then now, I have 3 files, the first one was the original template 'Sample.docx' and the remaining 2 has the same content (SampleProcessed.docx and SampleProcessedOut.docx).
It worked but It's pretty wasteful. Is there any way to this? Am I doing something wrong, perhaps am I opening the word document wrong?