Thursday, September 24, 2009

Groovy JDK (GDK): Text File to String

In my previous blog post, I briefly talked about the advantages of Groovy JDK (GDK) and specifically illustrated this by demonstrating how the GDK's File.deleteDir() method provides additional functionality beyond that provided by the standard SDK File.delete(). In this blog post, I demonstrate how another GDK extension function, File.getText(), makes extracting text from a file practically trivial.

When one wants to extract text from a file into a Java String, a typical approach is to use a BufferedReader. In fact, this is demonstrated in various forms in resources such as Java Developers Almanac 1.4 (swallows checked IOException), reading lines from text file, Reading and Writing Text Files, and How Do I Read a Text File? The How to Read File in Java example uses BufferedInputStream and DataInputStream.

In all of these examples, there is significant code involved to handle checked exceptions and resource management. Java-based one-line alternatives are discussed in the blog post Java One Liner - Reading a Text File at Once. Groovy, via its GDK, makes extracting a String from a File simple and convenient. The following Groovy code demonstrates how easy this is to use.

fileGetText.groovy

file = new File("TextFile.txt")
printf "$file's contents: ${file.getText()}"


The content of the TextFile.txt file is as shown next:

TextFile.txt

This is a text file.
This is only a text file.


The following screen snapshot shows the results of running the simple Groovy code against this text file:



All too easy!

Convenience methods such as File.getText() and File.deleteDir() make scripting with Groovy easier and more convenient.

No comments: