将多个文件附加到一个文件中 [英] Appending multiple files into one
问题描述
在一些位置有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中执行相同的操作....
//获取一个作家到您的新文件
新文件('/tmp/newfile.txt').withWriter {w - >
//对于每个输入文件路径
['/tmp/1.txt','/tmp/2.txt','/tmp/3.txt'].each { f - >
//获取输入文件的读取器
new File(f).withReader {r - >
//并将数据从输入写入输出
w<< r< '\\\
'
}
}
}
这样做的好处是(通过在每个源文件上调用 getText
),它不需要将整个文件加载到内存中,然后将其内容写入 newfile中
。如果您的某个文件很庞大,另一种方法可能会失败。
I have 4 different files in some locations like: D:\1.txt D:\2.txt D:\3.txt and D:\4.txt
I need to create a new file as NewFile.txt, It should contains all the contents present in the above files 1.txt, 2.txt,3.txt 4.txt.......
All Data should present in the New Single file(NewFile.txt)..
Please suggest me some idea to do the same in java or Groovy....
Here's one way to do it in 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'
}
}
}
The advantage of doing it this way (over calling getText
on each of the source files) is that it will not need to load the entire file into memory before writing its contents out to newfile
. If one of your files was immense, the other method could fail.
这篇关于将多个文件附加到一个文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!