3

如何将文件夹中的所有 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();
}

但是合并数千个文件需要几分钟,所以它是不可行的。

4

5 回答 5

4

使用 NIO,它比使用 inputstreams/outputstreams 容易得多注意:使用 Guava 的Closer,表示所有资源都安全关闭;更好的是使用 Java 7 和 try-with-resources。

final Closer closer = Closer.create();

final RandomAccessFile outFile;
final FileChannel outChannel;

try {
    outFile = closer.register(new RandomAccessFile(dstFile, "rw"));
    outChannel = closer.register(outFile.getChannel());
    for (final File file: filesToCopy)
        doWrite(outChannel, file);
} finally {
    closer.close();
}

// doWrite method

private static void doWrite(final WriteableByteChannel channel, final File file)
    throws IOException
{
    final Closer closer = Closer.create();

    final RandomAccessFile inFile;
    final FileChannel inChannel;

    try {
        inFile = closer.register(new RandomAccessFile(file, "r"));
        inChannel = closer.register(inFile.getChannel());
        inChannel.transferTo(0, inChannel.size(), channel);
    } finally {
        closer.close();
    }
}
于 2013-07-11T16:14:49.370 回答
2

因为这

  Integer b = null;
  while ((b = inFile.read()) != -1)
      outFile.write(b);

您的操作系统正在进行大量 IO 调用。read()只读取一个字节的数据。使用其他接受 a的读取方法byte[]。然后,您可以使用它byte[]来写入您的OutputStream. 类似地write(int),写入单个字节的 IO 调用也是如此。也改变它。

当然,您可以查看为您执行此操作的工具,例如 Apache Commons IO 甚至 Java 7 NIO 包。

于 2013-07-11T16:04:00.573 回答
0

尝试使用BufferedReaderBufferedWriter而不是逐个写入字节。

于 2013-07-11T16:04:55.097 回答
0

您可以使用 IoUtils 合并文件,IoUtils.copy() 方法将帮助您合并文件。

这个链接在java中可能是有用的合并文件

于 2013-07-11T16:05:57.323 回答
0

我会这样做!

  1. 检查操作系统

    System.getProperty("os.name")

  2. 从 Java 运行系统级命令。

    如果窗户

            copy /b *.txt merged.txt
    

    如果是 Unix

            cat *.txt > merged.txt
    

    或任何可用的最佳系统级命令。

于 2013-07-11T16:30:29.010 回答