rupert
rupert

Reputation: 59

groovy input into file iterate over map

Hi I got the map and loop iterate over the map.

def map = [file.txt : file2.txt,
file3.txt : fil4.txt,
file5.txt : file6.txt]

map.each { k,v ->
 collection = new file("k").readLines()
 collection2 = new file("v").readLines.findResult() 

def commons = collection.intersect(collection2)

}

I want every "commons" collection save into a file, not overwriting this file over the next iterations.

Is there a possibility to do such a thing in the loop?

Upvotes: 0

Views: 526

Answers (1)

Joxebus
Joxebus

Reputation: 205

Suppose you already have your list of files to merge, then the only thing you need to do is to write the lines of each file into the output file, you can do something like this:

def files = ['file1.txt', 'file3.txt', 'file2.txt']
def file = new File('output.txt')
def outputFile = file.newPrintWriter()

def mergeFile = { fileName ->   
    File sourceFile = new File(fileName) 
    sourceFile.eachLine{ line ->
        outputFile.println(line)
    }
}

files.each(mergeFile)

out.close()

This will merge the contents of all your files, there is another thing, you may need to specify the folder of the files, so I suggest to use the constructor that receives the folder.

File output = new File(folder, filename)

Upvotes: 0

Related Questions