Vicky
Vicky

Reputation: 17355

spring batch writing to a fixed format file

I have an Item Writer as below:

<beans:property name="lineAggregator">
<beans:bean class="org.springframework.batch.item.file.transform.FormatterLineAggregator">
        <beans:property name="fieldExtractor">
                <beans:bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
                 <beans:property name="names" value="column1, column2, column3, column4 " /> 
                </beans:bean>
            </beans:property>

            <beans:property name="format" value="%-8s%-12s%-11s%-16s" /> 
        </beans:bean>
    </beans:property>

As clear, I am writing 4 columns to a fixed format file with column lengths as 8, 12, 11 and 16 respectively.

However, say column 1 string is 14 characters instead of 8 characters, then the output file is blindly accomodating all the 14 characters by pushing the whole line ahead.

THIS IS A TEST

Expecting: 
THIS IS COL2STARTS

Getting: 
THIS IS A TESTCOL2STARTS

How to avoid this ?

Shouldn't the remaining characters get truncated and only the first 8 characters written ?

Do I need to put in validation in my code to strictly pass only 8 characters as expected by column ?

Upvotes: 2

Views: 10668

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

You have to set the precision along with the width. Try this formatter String:

<beans:property name="format" value="%-8.8s%-12.12s%-11.11s%-16.16s" /> 

See: FormatterLineAggregator, Formatter

Upvotes: 2

Related Questions