使用InputValueSwitch
. 这将匹配每行特定列中的值以确定RowProcessor
要使用的内容。例子:
为您需要处理的每种类型的记录创建两个(或更多)处理器:
final BeanListProcessor<FirstRow> firstProcessor = new BeanListProcessor<FirstRow>(FirstRow.class);
final BeanListProcessor<SecondRow> secondProcessor = new BeanListProcessor<SecondRow>(SecondRow.class);
创建一个InputValueSwitch
:
//0 means that the first column of each row has a value that
//identifies what is the type of record you are dealing with
InputValueSwitch valueSwitch = new InputValueSwitch(0);
//assigns the first processor to rows whose first column contain the 'firstRowType' value
valueSwitch.addSwitchForValue("firstRowType", firstProcessor);
//assigns the second processor to rows whose first column contain the 'secondRowType' value
valueSwitch.addSwitchForValue("secondRowType", secondProcessor);
像往常一样解析:
TsvParserSettings settings = new TsvParserSettings(); //configure...
// your row processor is the switch
settings.setProcessor(valueSwitch);
TsvParser parser = new TsvParser(settings);
Reader input = new StringReader(""+
"firstRowType\trecordValue1\n" +
"secondRowType\trecordValue1\trecordValue2");
parser.parse(input);
从您的处理器获取解析的对象:
List<FirstRow> firstTypeObjects = firstProcessor.getBeans();
List<SecondRow> secondTypeObjects = secondProcessor.getBeans();
输出将是*:
[FirstRow{recordType='firstRowType', recordValue1='recordValue1'}]
[SecondRow{recordType='secondRowType', recordValue1='recordValue1', recordValue2='recordValue2'}]
- 假设你在你的类中实现了一个理智的 toString()
如果要管理已解析对象之间的关联:
如果您FirstRow
应该包含为 type 的记录解析的元素SecondRow
,只需覆盖该rowProcessorSwitched
方法:
InputValueSwitch valueSwitch = new InputValueSwitch(0) {
@Override
public void rowProcessorSwitched(RowProcessor from, RowProcessor to) {
if (from == secondProcessor) {
List<FirstRow> firstRows = firstProcessor.getBeans();
FirstRow mostRecentRow = firstRows.get(firstRows.size() - 1);
mostRecentRow.addRowsOfOtherType(secondProcessor.getBeans());
secondProcessor.getBeans().clear();
}
}
};
- 以上假设您的
FirstRow
类有一个addRowsOfOtherType
将列表SecondRow
作为参数的方法。
就是这样!
您甚至可以混合搭配其他类型的RowProcessor
. 这里有另一个例子可以证明这一点。
希望这可以帮助。