我想通过使用java nio ZipFileSystem
更改单词/document.xml来修改作为字节数组获得的docx文档。我有以下代码(基于SO讨论如何使用Java编辑MS Word文档?):
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();
}
}
我想避免创建文件和写入磁盘,这是获得newFileSystem
调用中使用的URI所必需的。你能想出一种更有效的方法来获得这样的nio ZipFileSystem吗?
解决方案:
使用内存中的文件系统,如Google jimfs或marshall。类似于SO问题中的代码片段