从作为字节数组获得的 docx 文件创建 ZipFileSystem 而无需写入文件
Create ZipFileSystem from a docx file obtained as a byte array without writing to a File
我想修改 一个 docx 文档 - 作为字节数组获得 - 通过使用 java nio ZipFileSystem
更改 word/document.xml .
我有以下代码(基于 SO 讨论 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();
}
}
我想避免创建文件和写入磁盘,这是获取 newFileSystem
调用中使用的 URI 所必需的。有没有你能想到的更有效的方法来获得这样的 nio ZipFileSystem?
我想修改 一个 docx 文档 - 作为字节数组获得 - 通过使用 java nio ZipFileSystem
更改 word/document.xml .
我有以下代码(基于 SO 讨论 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();
}
}
我想避免创建文件和写入磁盘,这是获取 newFileSystem
调用中使用的 URI 所必需的。有没有你能想到的更有效的方法来获得这样的 nio ZipFileSystem?