Getting Groovy, Part III

Written By: James Williams

- 22 Aug 2006 -

Description: This tutorial is the third part of a series introducing the major features of Groovy, a dynamic scripting language for the Java Virtual Machine. We will be covering annotations, XML files, and file input/output.

  1. Annotation & Overloaded Constructors
  2. XML Files
  3. Files

Files

In lieu of the calls needed to several constructs in Java. In Groovy we need only one. The following code opens a file and prints its contents to standard output:

f = new File('someFile.txt]').newReader()
println f.getText()

The top line creates a BufferedReader, which in addition to the functions from the Java API, includes a getText() function. Similarily, we can write to a file just as easily:

f = new File('someFile.txt').newWriter()
f.writeLine("Hello, world!")
f.close()

Unlike the BufferedReader which can be left to be garbage-collected, BufferedWriters, as you probably already know, will need to be explicitly flushed or closed. Returning to our XML example, only a couple changes are needed to write the XML to a file:

f = new File('/home/jwill/Desktop/dd.xml').newWriter()
builder = new groovy.xml.MarkupBuilder(f)
builder.albums(owner:'James') {
        album(name:'Flowers') {
                photo(name:'rose.jpg')
        }
        album(name:'people') {
                photo(name:'john.jpg', desc:'picture of John')
        }
}
f.close()

We're done...for now. Sometime in the near future, I will demonstrate Groovy in a full-fledged application.

<< Previous