Thursday, November 29, 2007

Using Groovy to work with Files

One of the best applications of Groovy I have come across so far is working with Files. Using Groovy to read data from a file can not get any easier. If you are a Groovy skeptic this is the post for you. Using the maven-groovy-plugin, which allows you to mix Java and Groovy code seamlessly, you no longer have any more excuses (go here for a maven-groovy-plugin how-to).

Recently I was writing unit tests in Groovy for my Java code and I needed to read in the contents of a file for comparison. In Java this would look something like this:


public class FileTest {
public static void main(String[] args) {
try {
String file = "/workspace/sandbox/grvyfile/src/test.txt";
String line = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) !=null) {
System.out.println("sb.toString() = " + sb.toString());
} catch (FileNotFoundException e) {
System.out.println("e = " + e);
} catch (IOException e) {
System.out.println("e = " + e);

If you are still doing this STOP RIGHT NOW! This boiler plate code took me about 5 minutes to write. Since it's not something I do super frequently I don't commit this syntax to memory, and therefore almost always have to reference the API to remember to use things like

Would you like to see the Groovy equivalent? Make sure you don't blink; you might miss it.
def file = "/workspace/sandbox/grvyfile/src/test.txt"
println new File(file).text

That is all folks. In fact if you want to test this real quick, use the groovy command line like the following:
>cd /workspace/sandbox/grvyfile/src
>groovy -e "println new File('test.txt').text"

For those new to Groovy, .text is essentially shorthand for calling the .getText() method on the File object. The method getText() is one of the dozens of new methods added to the JDK (see the GDK for more).

Read my comments in this post (Java: Laugh or Cry, Your Choice...) by Kit Plummer for another good application of Groovy. Here I use the List GDK methods minus() and unique() to decrease the lines of code from ~27 to ~2.


bloid said...

Or course, in Java you *could* do:

String file = new Scanner( new File( "test.txt" ) ).useDelimiter( "\\Z" ).next() ;

if you want it in one line (and aren't trying to prove a point)

A.A.A said...

i respect Groovy, but i hate when people deliberately write 3 times more Java code than it should be to make people think they have a point..
if you need something quick and dirty, you should NOT use java anyway. Otherwise A good java developer should already have a Files.getFileAsString() method..

jlorenzen said...

I appreciate your comment triple a. However, I can honestly say I didn't "deliberately write 3 times more java code". Perhaps I might be a horrible programmer, but I am not a liar by intentionally trying to mislead people. I would rather you accuse me of being a bad programmer.
However though, I think you missed my core point: it doesn't really matter what the java equivalent code is, it's probably never going to be as easy as new File().text. Another fact you might be missing, is how many java programmers out there still continue to write crappy java code like I did? Probably more than a few.

Rob Madole said...

You can argue that anyone can write any kind of function to do any kind of thing. Sure, we can write a Files.getFileAsString() method but the discussion here is to point out what's built-in to the language. The point is out-of-the-box Groovy can do it with X number of lines. To do the same in Java takes 5 times that (or whatever the multiplier is.) I think you might be missing the point triple A.

Anonymous said...

@bloid no you cant you still need a main method and maybe imports so its not one line :D in groovy you dont need one.

products said...

China Wholesale has been described as the world’s factory. This phenomenom is typified by the rise ofbusiness. Incredible range of products available with China Wholesalers “Low Price and High Quality” not only reaches directly to their target clients worldwide but also ensures that wholesale from china from China means margins you cannot find elsewhere and buy products wholesaleChina Wholesale will skyroket your dressescheap naruto cosplayanime cosplaycheap Gemstone Jewelry

products said...

Women’s nike tn Shox Rivalry est le modèle féminin le plus tendance de baskets pour le sport. tn chaussuresConcernant la semelle :spyder jacketsCheap Brand Jeans Shop - True Religion Jeans cheap nike shox & Puma Shoes Online- tn nike,Diesel Jeans le caoutchouc extérieur, l’EVA intermédiaire Levis Jeanset le textile intérieur s’associent pour attribuer à la.ed hardy shirts pretty fitCharlestoncheap columbia jackets. turned a pair of double plays to do the trick.Lacoste Polo Shirts, puma basket, Burberry Polo Shirts.wholesale Lacoste polo shirts and cheap polo shirtswith great price.Thank you so much!!cheap polo shirts men'ssweate,gillette mach3 razor bladesfor men.As for Cheap Evisu JeansCheap Armani Jeanspolo shirtsPuma shoes