Java Reference
In-Depth Information
That's nearly 30 lines to do something extremely simple. All Java code has to be in a class
with a main method. The input stream System.in is available, but I want to read a
full line of data, so I wrap the stream in an InputStreamReader and wrap that in a
BufferedReader , all so I can call readLine . That may throw an I/O exception, so I
need a try / catch block for it. Finally, the incoming data is in string form, so I need to
parse it before adding up the numbers and printing the results.
Here's the corresponding Groovy version:
println 'Please enter some numbers'
System.in.withReader { br ->
println br.readLine().tokenize()*.toBigDecimal().sum()
}
That's the whole program. The withReader method creates a Reader implementation
that has a readLine method and automatically closes it when the closure completes.
Several similar methods are available for both input and output, including withReader ,
withInputStream , withPrintWriter , and withWriterAppend .
That was fun, but here's another version that has more capabilities. In this case, the code
has a loop that sums each line and prints its result until no input is given:
println 'Sum numbers with looping'
System.in.eachLine { line ->
if (!line) System.exit(0)
println line. split (' ')*.toBigDecimal().sum()
}
The eachLine method repeats the closure until the line variable is empty.
Groovy's contribution to file I/O is to add convenience methods that simplify the Java API
and ensure that streams or files are closed correctly. It provides a clean façade on the Java
I/O package.
Groovy makes input/output streams much simpler to deal with than in Java, so if I have a
Java system and I need to work with files, I try to add a Groovy module for that purpose.
That's a savings, but nothing compared to the savings that result from using Groovy over
Java when dealing with XML, as shown in the next section.
Search WWH ::




Custom Search