How can I get the number of lines and file name in itemProcessor - spring package

I am using spring package to parse my files. In ItemProcessor, I check the validity of incoming fields. If this is not the case, I want to throw a ValidationException and write the corresponding line with the wrong fields to the file. So, how can I find the number of lines and file name in ItemProcessor?

+4
source share
2 answers

Without seeing you in the configuration of ItemReader, I cannot be sure, but if you use something like FlatFileItemReader for parsing csv, if in strict mode it will check the number of columns.

Assuming the reader looks like this:

<bean id="iItemReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step"> <property name="linesToSkip" value="1"/> <property name="comments" value="#" /> <property name="encoding" value="UTF-8"/> <property name="lineMapper" > <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper"> <property name="lineTokenizer"> <bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer"> <property name="delimiter" value=","/> <property name="names"> <list > <value>First_Field</value> <value>Second_Field</value> </list> </property> <property name="strict" value="true"/> </bean> </property> <property name="fieldSetMapper"> <bean class="uk.co.package.FieldSetMapper"> <property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/> </bean> </property> </bean> </property> </bean> 

It will throw a FlatFileParseException exception for any rows that cannot be handled. This includes the line number and can be processed in the listener.

+1
source

As for the line number, you can create your own LineMapper and then save the line number in the business object. An example in which I keep the string raw (as is) along with the line number:

  DefaultLineMapper<OneRow> lineMapper = new DefaultLineMapper<OneRow>() { @Override public OneRow mapLine(String line, int lineNumber) throws Exception { return new OneRow(lineNumber, line); } }; 

Of course, you can already match your object, I had a need for the entire string not to be processed as input for my processors.

As a reference to the same idea: fooobar.com/questions/1464435 / ...

0
source

All Articles