将WordprocessingMLPackage保存到ByteArrayInputStream [英] Save WordprocessingMLPackage to ByteArrayInputStream

查看:656
本文介绍了将WordprocessingMLPackage保存到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.... ByteArrayInputStreamInputStream,您不能/不能写入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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆