groovyfixed-length-record

What's a good library for parsing fixed-length records in Groovy?


I want a library that I can give it a file and a config param of column length, name, and possibly type and from that get back a map of the columns of each row.

This isn't difficult thing to do on my own, but I would be surprised if there wasn't already a great solution. I've tried searching for one, but have had no luck.


Solution

  • You can always use FlatFileItemReader from Spring Batch that will return a structure like JDBC ResultSet.

    But it might be overkill and make it more complex. For Groovy I find it easy to read and write code like this:

    file = '''\
    JOHN      DOE       123       
    JANE      ROE       456       
    '''
    
    names = []
    file.eachLine { names << [
        first: it[0..9].trim(), 
        last:  it[10..19].trim(),
        age:   it[20..22].toInteger()
    ]}
    
    assert names[0].first == 'JOHN'
    assert names[1].age == 456