【发布时间】:2013-07-11 15:58:28
【问题描述】:
如何将文件夹中的所有 txt 文件合并为一个文件?一个文件夹通常包含成百上千个 txt 文件。
如果这个程序只在 Windows 机器上运行,我只会使用包含类似内容的批处理文件
copy /b *.txt merged.txt
但事实并非如此,所以我认为用 Java 编写它来补充我们所拥有的一切可能会更容易。
我写过这样的东西
// Retrieves a list of files from the specified folder with the filter applied
File[] files = Utils.filterFiles(downloadFolder + folder, ".*\\.txt");
try
{
// savePath is the path of the output file
FileOutputStream outFile = new FileOutputStream(savePath);
for (File file : files)
{
FileInputStream inFile = new FileInputStream(file);
Integer b = null;
while ((b = inFile.read()) != -1)
outFile.write(b);
inFile.close();
}
outFile.close();
}
catch (Exception e)
{
e.printStackTrace();
}
但是合并数千个文件需要几分钟,所以不可行。
【问题讨论】:
-
您一次读取一个字节...
-
哦,read() 没有尽可能多地阅读?这可能解释了为什么它这么慢
-
不,它读取单个字节(参见here,使用其他接受
byte[]的read() 方法。 -
@fge 一些机器仍在 java 6 上运行,但这应该不是问题。
-
好吧,即使 Java 6 也有
FileChannel,你应该充分利用它