How to merge >1000 xml files into one using Java

后端 未结 6 1789
予麋鹿
予麋鹿 2021-02-06 06:36

I am trying to merge many xml files into one. I have successfully done that in DOM, but this solution is limited to a few files. When I run it on multiple files >1000 I am getti

6条回答
  •  旧时难觅i
    2021-02-06 06:57

    Just do it without any xml-parsing as it doesn't seem to require any actual parsing of the xml.

    For efficiency do something like this:

    File dir = new File("/tmp/rootFiles");
    String[] files = dir.list();
    if (files == null) {
        System.out.println("No roots to merge!");
    } else {
            try (FileChannel output = new FileOutputStream("output").getChannel()) {
                ByteBuffer buff = ByteBuffer.allocate(32);
                buff.put("\n".getBytes()); // specify encoding too
                buff.flip();
                output.write(buff);
                buff.clear();
                for (String file : files) {
                    try (FileChannel in = new FileInputStream(new File(dir, file).getChannel()) {
                        in.transferTo(0, 1 << 24, output);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                buff.put("\n".getBytes()); // specify encoding too
                buff.flip();
                output.write(buff);
            } catch (IOException e) {
                e.printStackTrace();
            }
    

提交回复
热议问题