【问题标题】:Can XWPFDocument be converted to a Byte[] without saving it to a file first?XWPFDocument 可以在不先将其保存到文件的情况下转换为 Byte[] 吗?
【发布时间】:2020-02-20 12:27:14
【问题描述】:

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

【问题讨论】:

  • POIXMLDocument.writejava.io.OutputStream 作为参数。也可以是ByteArrayOutputStream
  • 你能再解释一下吗?

标签: arrays apache-poi xwpf


【解决方案1】:

XWPFDocument 扩展 POIXMLDocument 并且它的 write 方法采用 java.io.OutputStream 作为参数。那也可以是ByteArrayOutputStream。所以如果需要得到一个XWPFDocument作为一个字节数组,那么把它写入一个ByteArrayOutputStream,然后从方法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);
  } 

 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 2022-01-20
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    相关资源
    最近更新 更多