Reading a text file line by line
You may often find yourself with the need to read a file line-by-line and extract information from each processed line; think of a logfile. In this recipe, we will learn a quick way to read text files line-by-line using the efficient Groovy I/O APIs.
Getting ready
For the following code snippets, please refer to the Getting Ready section in the Reading from a file recipe, or just assume you have the file variable of the java.io.File
type defined somewhere in your script.
How to do it...
Let's see how to read all the text file's lines and echo them to the standard output.
To read all the lines at once, you can use the
readLines
method:def lines = file.readLines()
The lines is a collection (
java.util.ArrayList
) that you can iterate over with the usual collection iterator:lines.each { String line -> println line }
There is also the
eachLine
method, which allows doing the above without keeping an intermediate variable:file.eachLine { String line -> println...