我正在解析的文件之一由两个部分组成,我需要将它们逻辑拆分为两个不同的 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?