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 line }
There's more...
The java.io.Reader
and java.io.InputStream
class extensions also have the readLines
and eachLine
methods. For example, consider the following code:
file.withReader { Reader reader -> reader.eachLine { String line -> ... } }
This actually makes it possible for any Reader
or InputStream
to be processed line-by-line.
In a similar way, you can also read files, readers, or streams byte by byte with the help of the
eachByte
method:
file.eachByte { int b -> ... }
See also
The Processing every word in a text file recipe contains additional approaches to a text file content processing.
You can also find the following Javadoc and Groovydoc references useful: