从文件中读取字符串并使用Groovy将它们放入数组中

Inq*_*r21 6 arrays groovy input output

请原谅新手问题,但我正在学习如何使用Groovy做基本的东西.我需要知道如何从文件中读取单词(让我们调用文件list.txt)或从键盘中读取它们并将它们存储到一个字符串数组中(假设一个大小为10的数组)然后将它们打印出来.我该怎么做呢?我在这个问题上找到的例子对我来说并不清楚.

小智 12

实际上这很容易:

String[] words = new File('words.txt')
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用:

def words = new File('words.txt') as String[]
Run Code Online (Sandbox Code Playgroud)


tim*_*tes 11

怎么样:

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

// print them out
words.each {
    println it
}
Run Code Online (Sandbox Code Playgroud)