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.
Asked
Active
Viewed 2.9k times
10
-
Duplicate of http://stackoverflow.com/questions/5343689/java-reading-a-file-into-an-arraylist ? – Hubbitus Oct 07 '15 at 14:41
2 Answers
15
how about:
def words = []
new File( 'words.txt' ).eachLine { line ->
words << line
}
// print them out
words.each {
println it
}

tim_yates
- 167,322
- 27
- 342
- 338
-
1@Inquirer21 `it` is a keyword when using a Closure. `it` is the current Object of the iteration. You can rename `it` as has been done in the first part where it is renamed to `line` – Java Devil Dec 03 '13 at 01:13
-
1@Inquirer21 `it` is a reference to implicit objects in the closure; in this case, you can reference elements in `words` using `it` – raffian Dec 03 '13 at 01:14
-
Oh alright thanks. Does anyone know hot to read input from the keyboard into an array of strings? – Inquirer21 Dec 03 '13 at 01:20
-
1
13
Actually this is quite easy:
String[] words = new File('words.txt')
Alternatively, you can use :
def words = new File('words.txt') as String[]

melix
- 1,510
- 7
- 6
-
Note that this assumes, from your initial question, that you have one word per line. – melix Dec 03 '13 at 14:15