10

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.

Inquirer21
  • 339
  • 2
  • 5
  • 12

2 Answers2

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
    I guess I will need to ask that in a different question. – Inquirer21 Dec 03 '13 at 01:38
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