java - Supercsv 生成异常

标签 java csv supercsv

我的用例是从 CSV 读取对象,对对象执行一些修改,然后将它们写入另一个 CSV。我尝试修改 supercsv 示例如下,但收到 SuperCsvConstraintViolationException,我不确定如何解决。

public class ReadingWriting {

    private static final String CSV_READ_FILENAME = "src/test/resources/customers.csv";
    public static final String CSV_WRITE_FILENAME = "target/writeWithCsvBeanWriter.csv";

    public static void main(String[] args) throws Exception {
        readWithCsvBeanReader();
    }

    /**
     * Sets up the processors used for the examples. There are 10 CSV columns, so 10 processors are defined. Empty
     * columns are read as null (hence the NotNull() for mandatory columns).
     *
     * @return the cell processors
     */
    private static CellProcessor[] getProcessors() {
        final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust!
        StrRegEx.registerMessage(emailRegex, "must be a valid email address");
        final CellProcessor[] processors = new CellProcessor[]{
                new UniqueHashCode(), // customerNo (must be unique)
                new NotNull(), // firstName
                new NotNull(), // lastName
                new ParseDate("dd/MM/yyyy"), // birthDate
                new NotNull(), // mailingAddress
                new Optional(new ParseBool()), // married
                new Optional(new ParseInt()), // numberOfKids
                new NotNull(), // favouriteQuote
                new StrRegEx(emailRegex), // email
                new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints
        };
        return processors;
    }

    /**
     * An example of reading using CsvBeanReader.
     */
    private static void readWithCsvBeanReader() throws Exception {

        ICsvBeanReader beanReader = null;
        ICsvBeanWriter beanWriter = null;

        try {

            beanReader = new CsvBeanReader(new FileReader(CSV_READ_FILENAME), CsvPreference.STANDARD_PREFERENCE);
            beanWriter = new CsvBeanWriter(new FileWriter(CSV_WRITE_FILENAME), CsvPreference.STANDARD_PREFERENCE);

            final CellProcessor[] processors = getProcessors();

            // the header elements are used to map the values to the bean (names must match)
            final String[] header = beanReader.getHeader(true);
            beanWriter.writeHeader(header);

            CustomerBean customer;
            while ((customer = beanReader.read(CustomerBean.class, header, processors)) != null) {
                System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(),
                        beanReader.getRowNumber(), customer));

                beanWriter.write(customer, header, processors);//this line causes the below output
                /*
                lineNo=4, rowNo=2, customer=CustomerBean(customerNo=1, loyaltyPoints=0, mailingAddress=1600 Amphitheatre Parkway
                Mountain View, CA 94043
                United States)
                Exception in thread "main" Disconnected from the target VM, address: '127.0.0.1:60782', transport: 'socket'
                org.supercsv.exception.SuperCsvConstraintViolationException: duplicate value '1' encountered with hashcode 49
                processor=org.supercsv.cellprocessor.constraint.UniqueHashCode
                context={lineNo=2, rowNo=2, columnNo=1, rowSource=[1, John, Dunbar, Wed Jun 13 00:00:00 AEST 1945, 1600 Amphitheatre Parkway
                Mountain View, CA 94043
                United States, null, null, "May the Force be with you." - Star Wars, jdunbar@gmail.com, 0]}
                    at org.supercsv.cellprocessor.constraint.UniqueHashCode.execute(UniqueHashCode.java:78)
                    at org.supercsv.util.Util.executeCellProcessors(Util.java:93)
                    at org.supercsv.io.CsvBeanWriter.write(CsvBeanWriter.java:136)
                    at Reading.readWithCsvBeanReader(Reading.java:78)
                    at Reading.main(Reading.java:25)

                Process finished with exit code 1
                 */
            }
        } finally {
            if (beanReader != null) {
                beanReader.close();
            }
            if( beanWriter != null ) {
                beanWriter.close();
            }
        }
    }
}

最佳答案

在您的单元处理器中,您提到客户编号具有唯一的哈希代码。在文件中,我怀疑有一行具有相同的客户编号。

关于java - Supercsv 生成异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31823596/

相关文章:

java - 搜索最接近和小于的排序列表<Long>

database - 如何将数据从 .csv 导入到具有自动递增列的表中?

pdf - Powershell 获取超过 x 天的文件并移动它们

java - 使用 CsvBeanReader 读取列数可变的 CSV 文件

java - 如何配置 Super CSV 以引用除列名之外的所有值?

java - 我怎样才能告诉 SuperCSV 不要将空字符串映射到 null

java - 覆盖 Object.equals VS 重载它

尝试使用 MongoDB BulkWriteOperation 时出现 java.lang.IllegalStateException

java - JTextArea 动态扩展(不需要)

Powershell设置新本地用户强制更改密码