将WordprocessingMLPackage保存到ByteArrayInputStream [英] Save WordprocessingMLPackage to ByteArrayInputStream
问题描述
如何将org.docx4j.openpackaging.packages.WordprocessingMLPackage实例保存到ByteArrayInputStream中,然后可以从服务器下载它.
How can I save a org.docx4j.openpackaging.packages.WordprocessingMLPackage instance into ByteArrayInputStream, then It can be downloaded from server.
谢谢.
推荐答案
您无法保存到ByteArrayInputStream
.... ByteArrayInputStream
是InputStream
,您不能/不能写入InputStream
.
You cannot save to a ByteArrayInputStream
... ever. A ByteArrayInputStream
is an InputStream
and you don't / can't write to an InputStream
.
但是,您可以将内容写入ByteArrayOutputStream
,获取字节数组并为该数组创建ByteArrayInputStream
包装器.
However you can write something to a ByteArrayOutputStream
, get the byte array, and create a ByteArrayInputStream
wrapper for the array.
(我假设有一种方法可以将这些实例之一保存到OutputStream或Writer中……)
(I'm assuming that there is a way to save one of those instances to an OutputStream or Writer ...)
好吧,我的假设是错误的,并且WordprocessingMLPackage
唯一的save
方法保存到了File
. (我猜没有人得到有关如何设计灵活的I/O API的备忘录...)
Well, my assumption was wrong, and WordprocessingMLPackage
's only save
method saves to a File
. (I guess someone didn't get the memo on how to design flexible I/O apis ...)
But the source code ( here ) offers some clues on how you could implement it yourself. The method is as follows:
public void save(java.io.File docxFile) throws Docx4JException {
if (docxFile.getName().endsWith(".xml")) {
// Create a org.docx4j.wml.Package object
FlatOpcXmlCreator worker = new FlatOpcXmlCreator(this);
org.docx4j.xmlPackage.Package pkg = worker.get();
// Now marshall it
JAXBContext jc = Context.jcXmlPackage;
try {
Marshaller marshaller=jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
NamespacePrefixMapperUtils.setProperty(marshaller,
NamespacePrefixMapperUtils.getPrefixMapper());
marshaller.marshal(pkg, new FileOutputStream(docxFile));
} catch (Exception e) {
throw new Docx4JException("Error saving Flat OPC XML", e);
}
return;
}
SaveToZipFile saver = new SaveToZipFile(this);
saver.save(docxFile);
}
看起来您应该能够在帮助程序类中复制此代码,并对其进行调整以保存到OutputStream
而不是(特别是)FileOutputStream
.请注意,SaveToZipFile
类具有替代的save
方法,它们可以写入OutputStream
.
It looks like you should be able to copy this code in a helper class, and tweak it to save to a OutputStream
rather than (specifically) a FileOutputStream
. Note that the SaveToZipFile
class has alternative save
methods that write to an OutputStream
.
这篇关于将WordprocessingMLPackage保存到ByteArrayInputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!