可以将 XWPFDocument 转换为 Byte[] 而不先将其保存到文件吗?

Can XWPFDocument be converted to a Byte[] without saving it to a file first?

是否可以将 XWPFDocument 转换为 byte[]?我不想将它保存到文件中,因为我不需要它。如果有可能的方法,它会有所帮助

一个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);
  } 

 }
}