Java Accessing Word file DOCX zip and modifying document file

时间:2016-10-20 13:18:27

标签: java filesystems docx

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);
}

1 个答案:

答案 0 :(得分:0)

不确定我做错了什么,但没有一个回复。 我已根据专家交换的建议选择使用Docx4J!