The File.readLines() method easily returns the text contents of a given file similarly to the File.getText() method, but it returns these contents as a List of Strings with each String representing individual lines in the read-in file.
The following code snippet, a Groovy script called fileReadLines.groovy, demonstrates this Groovy function:
file = new File("TextFile.txt")
lines = file.readLines()
printf "$file's contents: $lines%n"
for (line in lines) printf "\t$line%n"
As in the previous blog posting,
TextFile.txt
is defined as shown below:
This is a text file.
This is only a text file.
When the above Groovy script, fileReadLines.groovy, is executed with the above text file, the results are as shown in the next screen snapshot.

As this output demonstrates, the returned list's contents can be displayed implicitly with square brackets or it can be iterated over to print each element in the list one-by-one.
Groovy JDK (GDK) makes writing text to a file as easy as reading it. The File.setText(String) method works as easily as the
File.getText()
method as demonstrated in the code listing below.
file = new File("TextOutputFile.txt")
file.setText("I am text looking for home.")
The output from this is shown in the next screen snapshot.

The Javadoc-based documentation for File.setText(String) reports that this method is a synonym for File.write(String). Note that both of these methods completely overwrite any existing text in the given file. If one wants to append new text to a file without obliterating existing text, the File.append(Object) method is useful.

Finally, GDK's File.size() method can be useful to see the file's size. The following code listing shows it.
file = new File("TextOutputFile.txt")
file.setText("I am text looking for home.")
file.append("I am also looking for a good home.")
printf "Size of file TextOutputFile.txt: ${file.size()}%n"
The output from running the above is shown next.

Conclusion
This blog post has demonstrated how easy it is to use
File.setText(String)
(and File.write(String)
), File.append(Object)
, File.readLines()
, and File.size()
. These extensions to the standard JDK File make manipulation of files easier for Groovy scripts.
No comments:
Post a Comment