【问题标题】:Merge multiple files using java使用java合并多个文件
【发布时间】:2020-09-06 17:30:30
【问题描述】:

我有一个部分文件。我必须将它们全部合并到文件中。我正在使用 RandomAccessFile 合并它们,它工作正常,但对于较大的文件,它非常慢。

这是我用来合并它们的代码:

    RandomAccessFile outFile = new RandomAccessFile(filename, "rw");

    long len = 0;

    //inFiles is a LinkedList<String> conatining all file part names

    for (String inFileName : inFiles) {

        RandomAccessFile inFile = new RandomAccessFile(inFileName, "r");
        int data;

        outFile.seek(len);

        while ((data = inFile.read()) != -1) {
            outFile.writeByte(data);
        }

        len += inFile.length();

        inFile.close();

    }


    outFile.close();

有没有比这种方法更快的合并文件的其他方法?... 请帮我优化这段代码。

【问题讨论】:

    标签: java optimization filestream file-handling randomaccessfile


    【解决方案1】:

    正如 Nemo_64 指出的那样,您一次使用 read() 字节,这在大文件上会非常慢。由于您并没有真正使用 RandomAccessFile 进行随机访问,因此仅使用顺序流 IO 就足够了,例如:

    try(OutputStream out = Files.newOutputStream(Paths.get(filename), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
        for (String inFileName : inFiles) {
            Files.copy(Paths.get(inFileName), out);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 2016-01-26
      • 2012-09-25
      • 2020-12-16
      • 2013-10-19
      • 2013-01-18
      相关资源
      最近更新 更多