How to Read Files in Groovy?

This article shows various ways of reading a text file in groovy.


Example 1:


This example uses the readLines method of the File class. readLines returns back a list of lines as Strings.
def myFile = new File("codelooru.txt")

def lines = myFile.readLines()
lines.each {line ->
 println line
}


Example 2:


This example uses the withReader method of the File class. withReader creates a BufferedReader with the File and passes it to the Closure. The reader can be used to read a line or characters. The reader is closed once it exits the Closure.
def myFile = new File("codelooru.txt")

myFile.withReader {reader ->
 println reader.readLine()
}


Example 3:


This example uses the eachLine method of File class. eachLine reads the file line by line and passes each line to the Closure. Again here, the reader is created implicitly and closed on exiting the Closure.
def myFile = new File("codelooru.txt")

myFile.eachLine {line ->
 println line
}


Example 4:


This example uses the eachLine method that also takes the line number. The line number starts at 1 and can be used to process the data based on line numbers. In the example below, the first 4 lines of the file are skipped.
def myFile = new File("codelooru.txt")

myFile.eachLine {line, number ->
 if(number <= 4)
  return
 println line
}


Example 5:


This example is the simplest of all methods. It uses the getText method of File to read the whole file into a String.
String fileContent = new File('codelooru.txt').text
println fileContent