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:
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 java.io.BufferedReader.import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
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) {
sb.append(line);
}
System.out.println("sb.toString() = " + sb.toString());
} catch (FileNotFoundException e) {
System.out.println("e = " + e);
} catch (IOException e) {
System.out.println("e = " + e);
}
}
}
Would you like to see the Groovy equivalent? Make sure you don't blink; you might miss it.
That is all folks. In fact if you want to test this real quick, use the groovy command line like the following:def file = "/workspace/sandbox/grvyfile/src/test.txt"
println new File(file).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).>cd /workspace/sandbox/grvyfile/src
>groovy -e "println new File('test.txt').text"
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.