0

I am trying to merge multiple docx files to one for a project. But I have done some reasearch and there is no way to find a code that can handle it in Java or Powershell. These are the things that come closest to what I want but it doesn't support multiple files.

package wordv2;

import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Wordv2 {

    public static void main(String[] args) {
        FileInputStream instream = null;

        FileOutputStream outstream = null;

        try {
            File infile = new File("C:\\jeux\\test.docx");

            File outfile = new File("C:\\jeux\\MyOutputFile.docx");

            instream = new FileInputStream(infile);

            outstream = new FileOutputStream(outfile);

            byte[] buffer = new byte[1024];

            int length;

            /*copying the contents from input stream to
             * output stream using read and write methods
             */
            while ((length = instream.read(buffer)) > 0) {
                outstream.write(buffer, 0, length);
            }

            //Closing the input/output file streams
            instream.close();
            outstream.close();

            System.out.println("File copied successfully!!");

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

Do you have any ideas to make it able to handle my request or do you know any other code that can do it?

RamenChef
  • 5,557
  • 11
  • 31
  • 43
Elaxe
  • 1

1 Answers1

0

I recommend using Apache POI its a great Java API for Microsoft documents.

As for Java part goes, you probably want a new file to merge all the existing ones into. If your files are all located in same directory on disk you can iterate through all the files in a directory and keep writing in the new file you created at the start. I recommend looking at https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walkFileTree-java.nio.file.Path-java.util.Set-int-java.nio.file.FileVisitor-

//create new word document
Files.walk(path).forEach(if a docx open it, write into a previously created and close)
//save new document
daddycool
  • 113
  • 2
  • 6
  • Sorry to ask but do u have an exempel ? I am a preaty new programmer and i try my best but it's not allways ez to see what other try to explain u And does ut way keep the formatting ? – Elaxe Sep 23 '16 at 20:41
  • @Elaxe https://www.tutorialspoint.com/apache_poi_word/apache_poi_word_quick_guide.htm – daddycool Sep 23 '16 at 21:00
  • @Elaxe i aslo suggest looking at http://stackoverflow.com/questions/25130419/how-to-copy-some-content-in-one-docx-to-another-docx-using-poi-without-losin – daddycool Sep 23 '16 at 21:08