如何通过逐个附加docx来读取2个Docx文件并写入第3个Docx文件

时间:2018-03-28 07:18:28

标签: java

我希望阅读2个Docx文件并写入第3个docx文件,方法是将第2个docx文件附加到第3个文件中。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class DocXReadAndWrite {

    public static void main(String[] args) throws IOException 
       {

         String fileName = "C:/Users/20123674/Downloads/DocumentScript/FileReadAndWrite/src/GUIDE - Docking Utility on SAMI EX.doc";
         String filename2 = "C:/Users/20123674/Downloads/DocumentScript/FileReadAndWrite/src/GUIDE - Docking Utility with SAMI Sync.doc";

         POIFSFileSystem fs = null;
         POIFSFileSystem fs1 = null;
         try 
         {
             fs = new POIFSFileSystem(new FileInputStream(fileName));
             fs1 =new POIFSFileSystem(new FileInputStream(filename2));
             HWPFDocument doc = new HWPFDocument(fs);
             HWPFDocument doc1 =new HWPFDocument(fs1);

             FileOutputStream fos = new FileOutputStream(new File("D:/newJapan5.doc"),true);
             doc.write(fos);
            //doc2.write(fos);

             doc1.write(fos);

            fos.flush();
            fos.close();

        }catch(Exception e)
         {
            e.printStackTrace();
         }


       }
}

1 个答案:

答案 0 :(得分:0)

试试这个,

public static void main(String[] args) throws Exception {

    StringBuilder sb = new StringBuilder();

    File file1 = new File("D:\\text1.txt");
    File file2 = new File("D:\\text2.txt");
    BufferedReader br = new BufferedReader(new FileReader(file1));
    String st;

    while ((st = br.readLine()) != null) {
        sb.append(st);
    }

    BufferedReader br1 = new BufferedReader(new FileReader(file2));

    String st1;
    while ((st1 = br1.readLine()) != null) {
        sb.append(st1);
    }

    BufferedWriter writer = new BufferedWriter(new FileWriter("text3.txt"));
    writer.write(sb.toString());
    writer.close();
}
}