Reading Strings from a file and putting them into an array with Groovy
25,528
Solution 1
how about:
def words = []
new File( 'words.txt' ).eachLine { line ->
words << line
}
// print them out
words.each {
println it
}
Solution 2
Actually this is quite easy:
String[] words = new File('words.txt')
Alternatively, you can use :
def words = new File('words.txt') as String[]
Author by
Inquirer21
Updated on July 09, 2022Comments
-
Inquirer21 almost 2 years
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.
-
Java Devil over 10 years@Inquirer21
it
is a keyword when using a Closure.it
is the current Object of the iteration. You can renameit
as has been done in the first part where it is renamed toline
-
raffian over 10 years@Inquirer21
it
is a reference to implicit objects in the closure; in this case, you can reference elements inwords
usingit
-
Inquirer21 over 10 yearsOh alright thanks. Does anyone know hot to read input from the keyboard into an array of strings?
-
Inquirer21 over 10 yearsI guess I will need to ask that in a different question.
-
melix over 10 yearsNote that this assumes, from your initial question, that you have one word per line.