使用Java合并多个文件

问题描述 投票:1回答:2

我有一部分文件。我必须将它们全部合并到文件中。我正在使用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
2个回答
0
投票

也许逐行读取逐字节插入的代码可以使其运行得更快


0
投票

正如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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.