2016-05-17 2 views
1

ich ein docx-Dokument ändern mag - erhalten als Byte-Array - durch das Wort ändern/document.xml ein java nio ZipFileSystem verwenden. Ich habe den folgenden Code (basierend auf SO Diskussion How to edit MS Word documents using Java?):ZipFileSystem aus einer docx-Datei als Byte-Array erhalten erstellen, ohne in eine Datei schreiben

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

Ich mag würde die Dateierstellung und das Schreiben auf der Festplatte, um die URI in newFileSystem Aufruf zu erhalten, benötigt zu vermeiden. Gibt es eine effizientere Möglichkeit, wie Sie ein solches ZipFileSystem bekommen können?

Antwort

Verwandte Themen