2016-05-17 60 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?

回答

相关问题