'Not able to display content of 2 files in one merged file by using FileOutputStream, instead it just shows content from first file

I am trying to read 2 docx files in byte arrays and trying to write it in one single docx file using FileOutputStream. Following is the code snippet I have used in groovy and grails.

byte[] firstFile = Files.readAllBytes(Paths.get("D:/MyDoc/firstFile.docx"));
byte[] secFile = Files.readAllBytes(Paths.get("D:/MyDoc/secFile.docx"));
FileOutputStream f = new FileOutputStream(new File("D:/MyDoc/mergedFile.docx"));
f.write(firstFile);
f.write(secFile);
f.close();

The issue is file size gets increased but the content in the merged file is only from the first file. Same code works for txt file but not for docx file.

I believe it should be some display/formatting issue which is why it is not showing the 2nd file content.



Solution 1:[1]

That is because docx is not a simple file format. Regarding raw data, the data of the second file is appended to the first file. But Word will read the header information at the beginning of the file, which will be the header info from the first file, and only interprets the first file. That is because there is some part in the header that tells word how big the document is. And word will only read that defined length of the document, ignoring everything else.

Some small example:

File1.docx

<HEADER>
  FILE_SIZE=3
<BODY>
1
2
3

File2.docx

<HEADER>
  FILE_SIZE=2
<BODY>
1
2

If you combine both, you will get:

<HEADER>
  FILE_SIZE=3
<BODY>
1
2
3
<HEADER>
  FILE_SIZE=2
<BODY>
1
2

But Word will start interpreting this file starting at the top. And after reading the header and the info that the file is only 3 lines long, it will stop after the first document.
This example is of course strongly simplified!!!

If you actually want to work with docx files in java, you should use a library that understands the word format and handles it appropriately. Like DOCX4J or Apache POI

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 3Fish