user5758361 user5758361 - 1 year ago 566
Java Question

Parsing a fixed format flat file using Spring or Java 8

So i have this flat file which i need to parse to get the various fields located within it. For example Position 0 to 2 is a header literal, position 3 to 10 is Name and so on.
I'm having a hard time trying to figure out how to go about this. Is there anything in Spring Batch that i can use to parse this fixed length file?
Sample flat file is given below:

H10000001140658760LMS 16TRSY16471A 402
I10000001140658760IT2016060310850028010700030719564-010 L00000072

So in the above format,

is the row literal,
is the receipt number,

is the supplier code and so on.

I need to map these to various fields like

  • position 0 to position 2 is the Literal,

  • position 3 to position 18 is receipt number,

  • position 18 to position 28 is supplier code.

Please advise.

So i tried using BeanIO with Spring Batch Integration but i'm getting an error while trying to create the reader.

I'm getting org.springframework.batch.item.ItemStreamException: Failed to initialize the reader.
Below is my code:

public BeanIOFlatFileItemReader<String> createBeanIOFlatFileItemReader(File file) throws Exception {
BeanIOFlatFileItemReader<String> reader = new BeanIOFlatFileItemReader<>();

reader.setResource(new FileSystemResource(file));
reader.setStreamMapping(new ClassPathResource("mapping.xml"));
reader.setStreamName("flatFile"); ExecutionContext());
return reader;

Jay Jay
Answer Source

You can do it by org.beanio.spring.BeanIOFlatFileItemReader


<bean id="fixedWidthFileReader" class="org.beanio.spring.BeanIOFlatFileItemReader" scope="step">
    <property name="streamMapping" value="classpath:META-INF/mapping.xml"/>
    <property name="streamName" value="flatFileStream" />
    <property name="resource" value="resource/inputFile"/></bean>


<stream name="flatFileStream" format="fixedlength">
<record name="flatFileContents" class="com.test.YourPojo" order="1">
    <field name="header" length="2" />
    <field name="name" length="15" />
    <field name="supplierCode" length="10" />

com.test.YourPojo is the domain model.

Note : length in mapping.xml will vary according to your requirement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download