簡體   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