Reading from a file
Groovy makes dealing with files a very pleasant business, thanks to a number of helper methods that work with standard Java's Reader
and Writer
, InputStream
and OutputStream
and File
classes.
In this recipe, we are going to look at the options available for reading a file in Groovy and accessing its content, mainly through the Groovy-enhanced File
class.
Getting ready
Let's assume we have a script that defines the following java.io.File
object:
def file = new File('poem.txt')
Of course, in order to be read, the poem.txt
file needs to exist in the same directory where our script is.
How to do it...
Let's explore some different ways to read the content of the
poem.txt
file.
In order to get the full text file content as a
java.lang.String
, you can use thegetText
method provided by the Groovy JDK extension:String textContent = file.text
file.text
is equivalent tofile.getText
, thanks to Groovy's special property getter handling syntax.You can also read it into memory as a byte...