2

我正在解析的文件之一由两个部分组成,我需要将它们逻辑拆分为两个不同的 bean。我发现 MultiBeanListProcessor 是一个很好的方法。我使用测试示例 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());          
        }
    }
}

这真的很好用。

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

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

4

1 回答 1

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;
    }
}

希望这可以帮助

于 2016-11-07T05:48:39.110 回答