可以将 XWPFDocument 转换为 Byte[] 而不先将其保存到文件中吗? [英] Can XWPFDocument be converted to a Byte[] without saving it to a file first?
问题描述
是否可以将 XWPFDocument
转换为 byte[]
?我不想将它保存到文件中,因为我不需要它.如果有可能的方法来做到这一点,它会有所帮助
is it possible to convert a XWPFDocument
to byte[]
? I don't want to save it into a file because I don't need it. if there is a possible way to do it, it would help
推荐答案
A XWPFDocument 扩展 POIXMLDocument 是 write 方法将 java.io.OutputStream 作为参数.这也可以是 ByteArrayOutputStream
.所以如果需要获取一个XWPFDocument
作为字节数组,则将其写入ByteArrayOutputStream
,然后从ByteArrayOutputStream.toByteArray.
A XWPFDocument extends POIXMLDocument and it's write method takes an java.io.OutputStream as parameter. That also can be a ByteArrayOutputStream
. So if the need is to get a XWPFDocument
as an byte array, then write it into a ByteArrayOutputStream
and then get the array from the method ByteArrayOutputStream.toByteArray.
示例:
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
public class CreateXWPFDocumentAsByteArray {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run=paragraph.createRun();
run.setBold(true);
run.setFontSize(22);
run.setText("The paragraph content ...");
paragraph = document.createParagraph();
ByteArrayOutputStream out = new ByteArrayOutputStream();
document.write(out);
out.close();
document.close();
byte[] xwpfDocumentBytes = out.toByteArray();
// do something with the byte array
System.out.println(xwpfDocumentBytes);
// to prove that the byte array really contains the XWPFDocument
try (FileOutputStream stream = new FileOutputStream("./XWPFDocument.docx")) {
stream.write(xwpfDocumentBytes);
}
}
}
这篇关于可以将 XWPFDocument 转换为 Byte[] 而不先将其保存到文件中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!