将openxmlformats-officedocument中的字节写入Java中的docx

时间:2017-07-31 18:39:00

标签: java file docx fileoutputstream

我有一个web服务,它获取将docx文件保存到内部文件夹的请求。 请求已经包含了我应该保存的文件的字节数组,但是,我正在努力使其工作。

问题:
当我将文件保存到文件夹并尝试打开docx时,它不会打开,并且Word表示由于文件无效而无法打开它。

所以,我读过一些帖子说Word文档是拉链的,如果是的话,我怎么能写这些字节才能正确生成docx文件?

请求中文件的类型是:

  

应用/ vnd.openxmlformats-officedocument.wordprocessingml.document

以下是代码。我想它不能使用FileOutputStream?

private void createAOLocalFile(byte[] document, String fileName) throws AOException {
    LOGGER.info("ENTER - createAOLocalFile(fileName: " + fileName + ")");

    try (FileOutputStream fileOutputStream= new FileOutputStream(new File(fileName));) {
        fileOutputStream.write(document);
        LOGGER.info("EXIT - createAOLocalFile");
    } catch (IOException ex) {
        LOGGER.error(String.format(exceptionMessage, "createAOLocalFile"), ex);
        throw new AOException(ex);
    } 
}

1 个答案:

答案 0 :(得分:0)

使用FileOutputStream时没有错,可能是您收到的数据已损坏。尝试使用Apache POI打开字节数组。

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.7-beta3</version>
    </dependency>

    import org.apache.poi.xwpf.usermodel.XWPFDocument;

[...]

    byte[] document; 
    XWPFDocument xWPFDocument = new XWPFDocument(new ByteArrayInputStream(document)); 

如果此语句抛出异常,那么您将收到已损坏文档的字节数组,然后Web服务出现问题。