将文档对象转换为字节[] [英] Converting Document object to Byte[]

查看:81
本文介绍了将文档对象转换为字节[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这样的init文档对象:

I am init Document object like this:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();

之后,我通过将数据插入到doc对象中构建XML文件。

After that I am building an XML file by inserting data to the doc object.

最后,我正在将内容写入我电脑上的文件。

Finally I am writing the contents to a file on my computer.

我的问题是如何将doc的内容写入 byte [] ?*

My question is how to write the contents of doc in to a byte[]?*

这是我如何将内容写入XML文件:

This is how i write the content to the XML file:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("changeOut.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);


推荐答案

通过 OutputStream 文件 StreamResult 构造函数。

 ByteArrayOutputStream bos=new ByteArrayOutputStream();
 StreamResult result=new StreamResult(bos);
 transformer.transform(source, result);
 byte []array=bos.toByteArray();

这篇关于将文档对象转换为字节[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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