JAVA - Merge将两个大型排序文件合并为一个排序

时间:2016-01-14 13:42:22

标签: java sorting merge

java中是否有jar文件或源代码实现两个大文件的合并连接为一个排序?或者在java中合并两个大文件的最佳方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:3)

您应该为此目的使用外部合并排序 要了解外部合并排序,请参阅此link

以下是代码link

从上面的链接中,只需使用您的情况下的合并操作:

 public static int mergeSortedFiles(List<File> files, File outputfile,
                final Comparator<String> cmp, Charset cs, boolean distinct,
                boolean append, boolean usegzip) throws IOException {
                ArrayList<BinaryFileBuffer> bfbs = new ArrayList<BinaryFileBuffer>();
                for (File f : files) {
                        final int BUFFERSIZE = 2048;
                        InputStream in = new FileInputStream(f);
                        BufferedReader br;
                        if (usegzip) {
                                br = new BufferedReader(
                                        new InputStreamReader(
                                                new GZIPInputStream(in,
                                                        BUFFERSIZE), cs));
                        } else {
                                br = new BufferedReader(new InputStreamReader(
                                        in, cs));
                        }

                        BinaryFileBuffer bfb = new BinaryFileBuffer(br);
                        bfbs.add(bfb);
                }
                BufferedWriter fbw = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream(outputfile, append), cs));
                int rowcounter = mergeSortedFiles(fbw, cmp, distinct, bfbs);
                for (File f : files)
                        f.delete();
                return rowcounter;
        }