我在某些位置有 4 个不同的文件,例如: D:\1.txt D:\2.txt D:\3.txt 和 D:\4.txt
我需要创建一个新文件 NewFile.txt,它应该包含上述文件 1.txt、2.txt、3.txt 4.txt 中存在的所有内容... ....
所有数据都应出现在新的单个文件 (NewFile.txt) 中..
请给我一些在 java 或 Groovy 中做同样事情的想法....
最佳答案
这是在 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'
}
}
}
这样做的好处(优于在每个源文件上调用 getText
)是在将其内容写入 之前不需要将整个文件加载到内存中新文件
。如果您的一个文件很大,则另一种方法可能会失败。
关于java - 将多个文件附加到一个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13065865/