将文件夹中的所有文本文件合并到一个文件中

时间:2013-07-11 15:58:29

标签: java file-io

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

但要合并数千个文件需要几分钟时间,因此不可行。

5 个答案:

答案 0 :(得分:4)

使用NIO,比使用输入流/输出流更容易 。注意:使用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();
    }
}

答案 1 :(得分:2)

因为这个

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

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

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

此链接可能有用merging file in java

答案 4 :(得分:0)

我会这样做!

  1. 检查操作系统

    System.getProperty( “os.name”)

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

    如果是windows

            copy /b *.txt merged.txt
    

    如果是Unix

            cat *.txt > merged.txt
    

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

相关问题