繁体   English   中英

Java从字节数组创建.docx文件

[英]Java create .docx file from byte array

我将.docx文件读取为字节数组,但是当我尝试再次将其保存为.docx文件时,该文件无法打开。

谁能解释为什么?

public static void main(String[] args) throws IOException {
    byte[] data = readFile("test.docx");
    System.out.println(data.length);

    try (FileOutputStream fos = new FileOutputStream("testCopy.docx")) {
        fos.write(data);
    }
}

这是readFile方法

public static byte[] readFile(String filePath) throws FileNotFoundException, IOException {
    File file = new File(filePath);
    byte[] bytes = new byte[(int) file.length()];
    try (DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)))) {
        dataInputStream.readFully(bytes);
    }

    return bytes;
}

您可能应该研究一下DataInputStream和FileInputStream之间的区别。

尝试使用FileInputStream代替DataInputStream并查看其工作方式。

try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
            fileInputStream.read(bytes);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM