2016-05-17 32 views
1

我想修改docx文檔 - 通過使用java nio ZipFileSystem更改單詞/ document.xml作爲字節數組獲得。 我有以下代碼(基於SO討論How to edit MS Word documents using Java?):從作爲字節數組獲取的docx文件中創建ZipFileSystem而不寫入文件

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

我想,以避免文件創建和寫入磁盤,以獲得URI需要newFileSystem調用中使用。有沒有一種更有效的方式來獲得這樣的nio ZipFileSystem?

回答

相關問題