本文介绍了是否可以将XWPFDocument转换为Byte []而不先将其保存到文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将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 ,它是写入方法将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 []而不先将其保存到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 07:15