Spectrum Spectrum - 1 month ago 9
Java Question

Java Accessing Word file DOCX zip and modifying document file

I am attempting to use a simple find and replace using example code provided.
This is in Beanshell in my app. I am getting an error on the line indicated;
Does so if I use 'env' or 'Null'!
The logit lines indicate that 'env' is populated and the path coming from a form does exist. (using UNC path to network share).

Error: "Typed variable declaration : Attempt to resolve method: newFileSystem() on undefined variable or class name: FileSystems : at Line: 46 : in file: inline evaluation of: FileSystems .newFileSystem ( docxUri , null )"

Help very much appreciated.

File zipfile = new File(thisProcess.getFieldValue("txt_Path"));
URI docxUri = new URI("jar:" + zipfile.toURI());

Map env = new HashMap();
importObject( env );
put("create", "false");
put("encoding", "UTF-8");

if(zipfile.exists() && !zipfile.isDirectory())
{
logit.info("Document EXISTS");
}

logit.info(env);

try
{
FileSystem zipFS = FileSystems.newFileSystem(docxUri, null); //ERROR ON THIS LINE
Path documentXmlPath = zipFS.getPath("/word/document.xml");

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(Files.newInputStream(documentXmlPath));

byte[] content = Files.readAllBytes(documentXmlPath);
String xml = new String(content, StandardCharsets.UTF_8);
xml = xml.replace("#DATE#", "2014-09-24");
xml = xml.replace("#NAME#", StringEscapeUtils.escapeXml("Sniper"));
content = xml.getBytes(StandardCharsets.UTF_8);
Files.delete(documentXmlPath);
Files.write(documentXmlPath, content);
}

Answer

Not sure what I have done wrong, but not a single reply. I have chosen to use Docx4J as suggested by Experts Exchange!

Comments