Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Strings from a file and putting them into an array with Groovy

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.

like image 375
Inquirer21 Avatar asked Dec 03 '13 00:12

Inquirer21


People also ask

How do you read a file and store it to an ArrayList in Java?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader.

How do I convert a text file to an array in Java?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.

How do I set the path of a file in Groovy?

Since the path changes machine to machine, you need to use a variable / project level property, say BASE_DIRECTORY, set this value according to machine, here "/home/vishalpachupute" and rest of the path maintain the directory structure for the resources being used.


2 Answers

Actually this is quite easy:

String[] words = new File('words.txt')

Alternatively, you can use :

def words = new File('words.txt') as String[]
like image 115
melix Avatar answered Sep 23 '22 23:09

melix


how about:

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

// print them out
words.each {
    println it
}
like image 21
tim_yates Avatar answered Sep 23 '22 23:09

tim_yates