Univocity - 是否可以使用MultiBeanListProcessor进行迭代?

时间:2016-11-06 20:47:37

标签: java csv univocity

我正在解析的一个文件包含两个部分,我需要逻辑上分成两个不同的bean。我发现MultiBeanListProcessor是一种很好的方法。我使用test example 14作为我的代码的来源。

给出以下配置:

public class Sample {

    public static void main(String[] args) throws IOException {     
        CsvParserSettings parserSettings = new CsvParserSettings();
        parserSettings.getFormat().setDelimiter('|');
        MultiBeanListProcessor processor = new MultiBeanListProcessor(Person.class, Address.class);
        String[] headers = new String[7];
        headers[0] = "id";      
        headers[1] = "firstName";
        headers[2] = "lastName";
        headers[3] = "city";
        headers[4] = "streetName";
        headers[5] = "houseNo";
        headers[6] = "houseAdd";
        String[] selectedFields = new String[5];
        selectedFields[0] = "firstName";
        selectedFields[1] = "lastName";
        selectedFields[2] = "city";
        selectedFields[3] = "streetName";
        selectedFields[4] = "houseAdd";
        parserSettings.setHeaders(headers);
        parserSettings.selectFields(selectedFields);       
        parserSettings.setProcessor(processor);
        parserSettings.setColumnReorderingEnabled(false);       
        CsvParser parser = new CsvParser(parserSettings);
        parser.parse(new FileReader("src/main/resources/input.csv"));

        List<Person> persons = processor.getBeans(Person.class);
        List<Address> addresses = processor.getBeans(Address.class);

        for (Person person : persons) {
            System.out.println(person.getFirstName());
        }   

        for (Address address : addresses) {
            System.out.println(address.getCity());          
        }
    }
}

这真的非常好。

不幸的是,输入文件很大,需要在内存中加载,我需要迭代而不是一次解析所有内容。在先前询问的question中,给出了如何迭代每个bean的答案。但是我没有设法将此逻辑/代码应用于此用例。

使用MultiBeanListProcessor时如何迭代每个bean?

1 个答案:

答案 0 :(得分:1)

目前唯一的选择是使用MultiBeanProcessor(而非MultiBeanListProcessor),这是抽象的并要求您提供方法的实现:

public void beanProcessed(Class<?> beanType, Object beanInstance, C context){
    // your code here
}

每次创建bean的新实例时,都会调用此方法,您可以根据需要处理对象实例。您可以使用context对象获取有关在需要时创建对象实例的记录的信息。一个非常简单的实现可能是:

private Person person;
private Address address;     

public void beanProcessed(Class<?> beanType, Object beanInstance, C context){
    if(beanType == Person.class){
         person = (Person) beanInstance;
    }
    if(beanType == Address.class){
         address = (Address) beanInstance;
    }
    if(person != null && address != null){
         //got all beans from a row, process them
         process(person, address);

         //clear up until you get the instances produced for the next record.
         person = null;
         address = null;
    }
}

希望这有帮助