Inquirer21
Inquirer21

Reputation: 349

Reading Strings from a file and putting them into an array with Groovy

Pardon the newbie question but I am learning how to do basic stuff with Groovy. I need to know how to either read words from a file (let's call the file list.txt) or from the keyboard and store them into an array of strings (let's say an array of size 10) and then print them out. How would I go about doing this? The examples I find on this matter are unclear to me.

Upvotes: 10

Views: 30884

Answers (2)

melix
melix

Reputation: 1530

Actually this is quite easy:

String[] words = new File('words.txt')

Alternatively, you can use :

def words = new File('words.txt') as String[]

Upvotes: 14

tim_yates
tim_yates

Reputation: 171084

how about:

def words = []
new File( 'words.txt' ).eachLine { line ->
    words << line
}

// print them out
words.each {
    println it
}

Upvotes: 15

Related Questions