Wednesday, January 21st, 2009...9:42 am

Easily Creating Fixed Length Flat Files With Groovy

Jump to Comments

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.

The Plan

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.

The Code

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.

import groovy.sql.Sql


def fileName = “FLATFILE” + String.format(‘%tY%
fileDef.each{ k,v-> writer.append ((row[k] ?: ” “).padRight(v))}
writer.append “\n”



  • Using File.withWriter would be better because it will close resources on exception.

    new File(filename).withWriter { w ->

  • I see a lot of interesting posts on your blog. You have to spend a lot of time
    writing, i know how to save you a lot of work, there is a tool that creates unique,
    SEO friendly posts in couple of seconds, just
    type in google – k2 unlimited content

  • I read a lot of interesting articles here. Probably you spend a lot of time writing, i know how to save you a lot of work, there is an online tool that creates high quality,
    google friendly posts in seconds, just search in google – laranitas free content source

Leave a Reply