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.
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.
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.
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.
Actually this is quite easy:
String[] words = new File('words.txt')
Alternatively, you can use :
def words = new File('words.txt') as String[]
how about:
def words = []
new File( 'words.txt' ).eachLine { line ->
words << line
}
// print them out
words.each {
println it
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With