Dani
Dani

Reputation: 47

How to convert each line of a file into list(sublist) in groovy?

I am relatively new to groovy. I have been trying to read .txt file and convert each line into the list. I read the file and convert it into a list of lines. I need to convert each line into a list and iterate through each line to make bigger list. Here is the sample code

 File file = new File("C:Roster1.txt")

    if( !file.exists() ) {
        println "File does not exist"
    } else {

        file.splitEachLine("\n"){string->
            string.each{r ->
            r = r.split(' ')
            println r}
        }
    }

I even tried to use def lines = file.readLines() // this creates list of lines, but not the list of string contents in each lines.

Upvotes: 2

Views: 3019

Answers (1)

tim_yates
tim_yates

Reputation: 171154

You can just do:

if(!file.exists()) {
    println "File does not exist"
}
else {
    (file as List).each {
        println it.split(' ')
    }
}

Upvotes: 2

Related Questions