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[]
Share:
25,528
Inquirer21
Author by

Inquirer21

Updated on July 09, 2022

Comments

  • Inquirer21
    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
    Java Devil over 10 years
    @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
  • raffian
    raffian over 10 years
    @Inquirer21 it is a reference to implicit objects in the closure; in this case, you can reference elements in words using it
  • Inquirer21
    Inquirer21 over 10 years
    Oh alright thanks. Does anyone know hot to read input from the keyboard into an array of strings?
  • Inquirer21
    Inquirer21 over 10 years
    I guess I will need to ask that in a different question.
  • melix
    melix over 10 years
    Note that this assumes, from your initial question, that you have one word per line.