I’m trying to replace some words in word document on the same file.
public class WordEdit {
static String DocX;
static String DocX2;
public static void main(String[] args) throws Exception {
DocX = "C:\Users\aneesh.shaik\Downloads\I&TF-0206-2024.docx";
DocX2 = "D:\Automation\Files\I&TF-0206-2024.docx";
XWPFDocument doc = new XWPFDocument(OPCPackage.open(DocX));
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph p : cell.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
String text = r.getText(0);
if (text != null && text.contains("Aneesh423")) {
text = text.replace("Aneesh423", "Aneesh");
System.out.println("find 2");
r.setText(text,0);
}
}
}
}
}
}
doc.write(new FileOutputStream(DocX)); // Getting error on this line
doc.close();
}
}
If I write it on DocX2 file location, then its working properly. But if I want to write it on same document on DocX file location, then getting error.
Please help to resolve this issue.