简体   繁体   中英

How to use FlatFileItemReader in spring batch for items separated by space (multiple records on single line)?

Spring batch FlatFileItemReader supports two files formats by default, Fix length and delimiter separated. eg

id name email 
1  name1  name1@abc.com
2  name2  name@abc.com

So it will consider each line as an item and fields as properties of item (domain) object.

My input file has just ids separated by space or comma as I just need ids (or it could be anything unique for each item like username or email etc) eg

1,2,3,4,5,6
7,8,9, ...... so on

or

username1, username2, username3, username4 .. so on

How can I use FlatFileItemReader to consider each id as an each item ie in short multiple records on single line ? Or is there any other way to achive this ?

You can use your custom LineMapper to implement the logic as per your requirement to separate the items from each line.

Here is the sample code that will return the list of Ids either separated by comma or space or both in each line.

import java.util.ArrayList;
import java.util.List;

import org.springframework.batch.item.file.LineMapper;

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

    public List<String> mapLine(String line, int lineNumber) throws Exception {

        List<String> list = new ArrayList<String>();
        for (String s1 : line.split(",")) {
            for (String s2 : s1.trim().split(" ")) {
                list.add(s2.trim());
            }
        }
        return list;
    }

}

overriding default buffered reader can also solve this issue. So, in your custom reader, you don't proceed to next line if you haven't finished reading all objects in same line.

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