1

I want to modify a docx document - obtained as a byte array - by changing the word/document.xml using a java nio ZipFileSystem. I have the following code (based on SO discussion How to edit MS Word documents using Java?):

public static void modifyDocxContent(byte[] docx, byte[] newContent)  {
    try {
        // Create a Word File from byte[]
        File docxFile = new File("C:\\test\\simple.docx");
        Path docxPath = docxFile.toPath();
        Files.write(docxPath, docx);

        // Create jar URI for the same Word file
        URI docxUri = URI.create("jar:file:/C:/test/simple.docx");  

        // Create a zip FileSystem for word file and modify content in it
        Map<String, String> zipProperties = new HashMap<>();
        zipProperties.put("encoding", "UTF-8");
        zipProperties.put("create", "false");   

        try (FileSystem zipFS = FileSystems.newFileSystem(docxUri, zipProperties)) {
            Path documentXmlPath = zipFS.getPath("word", "document.xml");
            Files.delete(documentXmlPath);
            Files.write(documentXmlPath, newContent, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.SYNC);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } 
}

I would like to avoid the File creation and writing to disk, needed in order to obtain the URI used in newFileSystem call. Is there a more efficient way you could think of for getting such nio ZipFileSystem?

Community
  • 1
  • 1
Caroh
  • 113
  • 8

1 Answers1

0

Solution:
Use an in memory file system such as Google jimfs or marshall. Code snippet similar to the one in SO question

Community
  • 1
  • 1
Caroh
  • 113
  • 8