我偶然发现了 supercsv 库,它看起来是一个非常好的作品。 但是,我有一个问题,我无法通过他们网站上提供的文档来回答,想知道这里是否有人可以提供帮助。
基本上,我有一个 csv 文件,其中有一列仅在另一列设置为特定值时才出现。 因此,示例如下:
是出生日期,出生日期
是的,1985年5月11日
没有
是的,1999年12月1日
没有
没有
你明白我的意思了。有没有一种方法可以创建一个单元处理器,可以考虑这种依赖性,并在发现这样的行时抛出异常:
否,1968 年 9 月 12 日
干杯
最佳答案
似乎这个问题已经在 Super CSV 论坛上得到了回答: http://sourceforge.net/p/supercsv/feature-requests/25/#30a5
复制帖子以防链接失效:
I think you're asking whether you can validate that Items have a parentPartNumber but skip that validation for Products. This is essentially cross-validation (validation involving more than 1 column).
The only way I can think of to achieve this with cell processors is to write a custom cell processor that inspects the value in another column, and decides what to do based on the value. Every cell processor has access to the
CsvContext
, which contains the raw (unprocessed) values.So you can write a processor such as the following. It behaves like
Optional
if the value in a given column (where column numbers start at 1) equals the value its expecting. Otherwise, it simply delegates to the next processor in the chain.
package example;
import java.util.List;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.util.CsvContext;
public class OptionalIfOtherColumnEquals extends Optional {
private final int column;
private final Object constantValue;
public OptionalIfOtherColumnEquals(int column,
Object constantValue) {
super();
this.column = column;
this.constantValue = constantValue;
}
public OptionalIfOtherColumnEquals(int column,
Object constantValue,
CellProcessor next) {
super(next);
this.column = column;
this.constantValue = constantValue;
}
@Override
public Object execute(Object value, CsvContext context) {
// unprocessed row
List<Object> row = context.getRowSource();
// optional if other column matches value
if (row.get(column - 1).equals(constantValue)){
return super.execute(value, context);
}
// otherwise continue to next processor
return next.execute(value, context);
}
}
I replaced the processor definition for the parentPartNumber column with new OptionalIfOtherColumnEquals(2, "Product", new IsValueIn(partNumbers)) and it works for Products and Items but it fails validation on the Packages at the end of the file.
I'll leave that as an exercise for you to solve, but you can see that you can achieve cross-validation if you really have to. Hope this helps.
关于java - 依赖于多列的 SuperCSV Cellprocessor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20492764/