Sunday, July 1, 2012

Why I like Java in Groovy

For many people the option in Groovy to switch to Java seems useless and as an extra burden. But I find it very useful, with great potential (just like option to inline assembler in C or Pascal, in the good old days). And I have an example where I can show you how I used it in real life.
   Because for the past year I was responsible for our builds, I wrote some scripts to simplify the tedious and error prone work. First I wrote some bash and Ant scripts, which I latter ported to Gradle. I found Gradle to be more suitable for the tasks our build required.
   Recently I was writing a task to manipulate some binary files, when I run into an odd problem with Gradle/Groovy. With following implementation:


// wrong implementation

File inputFile = new File("location.tmp");
locationTemplate = inputFile.getText();
byte[] tmplContent = locationTemplate.getBytes();
byte[] resultContent = new byte[ tmplContent.length];

//do something with the content and copy it to resultContent
f = new File(metaFilePath);
f.write(new String(resultContent));


Some bytes/characters were changed during saving, which was a problem. So I changed it to following implementation:

//working implementation
File fin = new File("location.tmp");
long length = fin.length();
byte[] tmplContent = new byte[(int)length];
FileInputStream fis = new FileInputStream(fin);
fis.read(tmplContent);
fis.close();

//do something with the content
FileOutputStream fos = new FileOutputStream(new File(metaFilePath));
fos.write(resultContent);
fos.close();


So I came to a point where I was thankful to Groovy and Gradle that I can switch seamlessly between Groovy and Java.