简体   繁体   中英

How do I write a header and trailer to an existing file using spring batch without overwriting the information in that file?

I have multiple files in a directory and those files have contents in them that will vary in size.

Ex File 1:

line 1.data data data

Ex File 2:

line 1.data data data

line 2.data data data

line 3.data data data

I need to append a header to the top of the file and a trailer to the bottom without overriding the data in the files using spring batch.

Ex File 1:

HEADERFOOTERZZZZZZZZ0000000XXXXXXXX

line 1.data data data

HEADERFOOTERZZZZZZZZ0000000XXXXXXXX

Ex File 2:

HEADERFOOTERZZZZZZZZ0000000XXXXXXXX

line 1.data data data

line 2.data data data

line 3.data data data

HEADERFOOTERZZZZZZZZ0000000XXXXXXXX

The writer portion of my context file has the below general configuration, but no header nor trailer is being added to the existing test files. How do I configure my flatFileItemWriter to add a header and trailer to an existing file without overwriting the file's existing data?

<bean id="addHeaderTrailerWriter" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
        <property name="lineAggregator" ref="lineAggregator" />
        <property name="resource" value="file://#{stepExecutionContext['WORK.FILE.NAME']}" />
        <property name="headerCallback" ref="headerFooterCallback" />
        <property name="footerCallback" ref="headerFooterCallback" />
    </bean>
    <bean id="lineAggregator" class="org.springframework.batch.item.file.transform.PassThroughLineAggregator"/>
    <bean id="headerFooterCallback" class="headerFooterCallbackClass">
        <constructor-arg name="headerFooter" ref="customHeaderFooter" />
    </bean>
    <bean id="customHeaderFooter" class="customHeaderFooterImplClass" > 
        <property name="input1" value="HEADERFOOTER" />
        <property name="input2" value="ZZZZZZZZ" />
        <property name="inout3" value="00000000" />
        <property name="input4" value="XXXXXXXX" />
    </bean>

Overriding the file itself to add a header and a footer is not possible. There is an append mode in the FlatFileItemWriter but that won't insert a header before the current data in the file "inline".

What you can do is create a job with two steps:

  • step1 (chunk oriented): read from the file and write to another file adding the header and footer
  • step2 (tasklet): delete the original file and rename the copy.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM