Wednesday, January 21st, 2009...9:42 am
Easily Creating Fixed Length Flat Files With Groovy
Here’s an (I think elegant) way to create flat files with Groovy.
I want this script to be easy to read by future developers. So if someone wants to know what the format of the file is they can see it just by opening the script.
Classes We’ll Use
- SQL: We’ll use this library to access the database, it has some nice closure methods like eachRow which make iterating over results easy.
- String: Groovy includes a string class that has some nice methods like padRight and padLeft, handy for making fixed length files.
- File Writer: The easiest way to create files in java.
Define our file in a map at the top of the file, it will be SQL Alias Name : Length.
Execute our SQL, for each row iterate through our file definition map and pad each value by the appropriate length.
Pretty self explanatory — a few neat groovy things we use in this script:
- Triple quotes for a multiline string (our sql)
- The format method to easily format a date (bye bye simple date format) for the file name
- The elvis operator
?:makes the results null safe so we can call padRight.
- The each method on Groovy’s Map that accepts a closure, we use that to iterate through our file definition.
def fileName = “FLATFILE” + String.format(‘%tY%