Pregunta

I have the file with below format. Each line has single item e.g.

RIC1
RIC2
RIC3
.
.
.
so on

I am using FlatFileItemReader to read these items. This is configuration

<beans:bean id="myLineMapper"
    class="com.st.batch.foundation.MyLineMapper" />

<beans:bean id="myFileItemReader"
    class="org.springframework.batch.item.file.FlatFileItemReader"
    p:resource="file:${spring.tmp.batch.dir}/somename-#{jobParameters[date]}/items.txt"
    p:lineMapper-ref="myLineMapper" scope="step" />

This is my line mapper,

public class MyLineMapper implements LineMapper<List<String>> {

    public List<String> mapLine(String line, int lineNumber) throws Exception {
        List<String> list = new ArrayList<String>();        
        list.add(line.trim());
        return list;
    }

}

In my Item writer, I am getting items wrapped with square brackets. I have no idea where these brackets are added ?

public class ImportExchangeItemWriter<T> implements ItemWriter<T>{

    public void write(List<? extends T> items) throws Exception {
        for (T item : items) {
            System.out.println(item);

        }

}

Below is the output:

[RIC1]
[RIC2]
[RIC3]
.
.
.
so on

How are these brackets added to the items ? Is there any way to remove it ?

¿Fue útil?

Solución

This is happening because you are missing a FieldSetMapper to map the content of the list you are seeing to the first and only element you want.

public class MyFieldSetMapper implements FieldSetMapper<String> {
    @Override
    public String mapFieldSet(FieldSet fieldSet) throws BindException {
        String myItem = fieldSet.readString(0);
        return myItem;
    }
}

and in the XML config use the DefaultLineMapper that is expecting a FieldSetMapper:

<bean name="sampleLineMapper"
      class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
    <property name="fieldSetMapper" ref="sampleMapper" />
    <property name="lineTokenizer" ref="sampleLineTokenizer" />
</bean>

<bean name="sampleLineTokenizer" class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer" />

<bean name="sampleMapper" class="path.to.MyFieldSetMapper" />

Otros consejos

It worked by using

I don't need to create custom line mapper, there is default implementation org.springframework.batch.item.file.mapping.PassThroughLineMapper.

You get those square brackets because your LineMapper, in its mapLine() method, returns a List<String>. So, every line that's being read is considered to be a List<String>. In Java, printing a List is using by default square brackets to delimit the contents of the list.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top