Parsing a text file in Java can be very difficult. Its one of the first things you are taught to do with Java. And it is not simple. Here's a simple snippet which would read a file from java and print out each line from the file:
package javaapplication2;Here's the same piece of code written in Groovy.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fstream = new FileInputStream("/home/umesh/febsec.txt");
DataInputStream in = new DataInputStream(fstream);
String strLine;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
}
}
package javaapplication2I am sure I gloss over some things, which make Java robust and all that good stuff. But that's the essence - simple and dynamic. Of course, no typing is also good.
new File("/home/umesh/febsec.txt").eachLine {println it}
The learning curve for me was minimal - I spent some time reading about Groovy, courtesy Google and no I don't Bing. I had a parser to write and I was able to cobble it together within the 2 hours. What astounded me were 2 things which I never get to do easily with Java:
- Having class files without all that overhead of imports and packages - just so you know,my original script has no package line. I am not sure how this all works, but I am going to find out, because this simple thing means I get to write command line apps in Java with very little overhead and lots of Groovy magic.
- Closures - I never quite understood what closures meant. It's difficult to treat functions as first class objects. But this example definitely got me interested. Much has been written about closures, which I won't repeat, suffice to say they are pretty powerful and compact.
What can I do with it? I am not sure. I don't want to fall into the 'there are so many things to do, I'm sure I will find one' hole. Been there too many times. This is not to say I believe Groovy can solve every problem. It has its own set of vulnerabilities. And I definitely do not like the idea of having a dynamic language handle ,say, financial transactions. But since I know Java, using this as my primary scripting tool should make automation a breeze.
No comments:
Post a Comment