将多个文件合并为一个

Bha*_*A N 8 java string groovy file

我在一些位置有4个不同的文件,如:D:\ 1.txt D:\ 2.txt D:\ 3.txt和D:\ 4.txt

我需要创建一个新文件NewFile.txt,它应该包含上述文件中存在的所有内容1.txt,2.txt,3.txt 4.txt .......

所有数据都应出现在New Single文件(NewFile.txt)中.

请建议我在java或Groovy中做同样的想法....

tim*_*tes 9

这是Groovy中的一种方法:

// Get a writer to your new file
new File( '/tmp/newfile.txt' ).withWriter { w ->

  // For each input file path
  ['/tmp/1.txt', '/tmp/2.txt', '/tmp/3.txt'].each { f ->

    // Get a reader for the input file
    new File( f ).withReader { r ->

      // And write data from the input into the output
      w << r << '\n'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这种方式(通过调用getText每个源文件)的优点是,在将内容写入之前,不需要将整个文件加载到内存中newfile.如果您的某个文件非常庞大,另一种方法可能会失败.