- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定这个 bean:
@Data
public class Contact {
@PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[A-Za-z]{3,8}$")
@CsvBindByName(column = "Contact First Name", required = true)
private String contactFirstName;
@PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[0-9]{10}$")
@CsvBindByName(column = "Phone Number", required = true)
private String phone;
}
CsvToBeanBuilder() 配置如下:
...
final CsvToBean<Contact> beans = new CsvToBeanBuilder<Contact>(
Files.newBufferedReader(csvFilePath, StandardCharsets.UTF_8))
.withType(Contact.class)
.withThrowExceptions(false)
.build();
this.contacts = beans.parse();
beans.getCapturedExceptions().stream().forEach(ex -> System.out.println(ex.getMessage()));
...
如果我给它一个像这样的文件:
Contact First Name,Phone Number
joe1,1234567890
jane,123456789
我(正确地)收到了这些错误消息:
Field userName value "joe1" did not match expected format of ^[A-Za-z]{3,8}$
Field phone value "123456789" did not match expected format of ^[0-9]{10}$
由于我将这些消息传回给用户,我希望错误消息使用 CSV 列名而不是 bean 的字段名,并且如果我可以提供自定义验证消息——可能作为附加字段@PreAssignmentValidator? -- 这样消息看起来像:
Field 'User Name' value "joe1" did not match expected format of '3 - 8 alphabetic characters'
Field 'Phone Number' value "123456789" did not match expected format of '10 digits'
关于如何在不编写一些自定义逻辑来转换这些消息的情况下执行此操作的任何建议/指示?
谢谢!
根据@andrewjames 的建议更新了代码
@Getter
public class Contact {
//@PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[A-Za-z]{3,8}$")
@CsvBindByName(column = "Contact First Name", required = true)
private String contactFirstName;
//@PreAssignmentValidator(validator = MustMatchRegexExpression.class, paramString = "^[0-9]{10}$")
@CsvBindByName(column = "Phone Number", required = true)
private String phone;
public void setContactFirstName(String contactFirstName) throws CsvValidationException {
if (contactFirstName.length() < 3 || contactFirstName.length() > 8) {
throw new CsvValidationException("'Contact First Name' must be between 3-8 characters long");
}
this.contactFirstName = contactFirstName;
}
public void setPhone(String phone) throws CsvValidationException {
if (phone.length() != 10) {
throw new CsvValidationException("'Phone Number' must be between 10 digits long");
}
this.phone = phone;
}
}
public class ContactTest {
private static final String HEADER = "Contact First Name,Phone Number\n";
@Test
public void test() throws Exception {
String data = HEADER
+ "jo,1234567890\n"
+ "al,123456789"; // This row should generate two exceptions
CsvToBean<Contact> csvToBean = new CsvToBeanBuilder<Contact>(new StringReader(data))
.withType(Contact.class)
.withThrowExceptions(false)
// .withExceptionHandler(new ExceptionHandlerQueue()) // Tried this way after commenting previous line
.build();
List<Contact> beans = csvToBean.parse();
csvToBean.getCapturedExceptions().stream().forEach((ex) -> {
System.out.println((int) ex.getLineNumber() + " -- " + ex.getMessage());
});
}
}
但现在 csvToBean.parse() 只是抛出异常。对于第二行,我只得到第一个异常(exception):
Exception in thread "pool-1-thread-2" java.lang.RuntimeException: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:111)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:290)
at com.opencsv.bean.AbstractBeanField.setFieldValue(AbstractBeanField.java:182)
at com.opencsv.bean.AbstractMappingStrategy.setFieldValue(AbstractMappingStrategy.java:607)
at com.opencsv.bean.AbstractMappingStrategy.populateNewBean(AbstractMappingStrategy.java:330)
at com.opencsv.bean.concurrent.ProcessCsvLine.processLine(ProcessCsvLine.java:131)
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:87)
... 3 more
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.opencsv.bean.FieldAccess.lambda$determineAssignmentMethod$3(FieldAccess.java:79)
at com.opencsv.bean.FieldAccess.setField(FieldAccess.java:115)
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:286)
... 8 more
Caused by: com.opencsv.exceptions.CsvValidationException: 'Contact First Name' must be between 3-8 characters long
at org.lotia.example.entity.Contact.setContactFirstName(Contact.java:23)
... 15 more
Exception in thread "pool-1-thread-1" java.lang.RuntimeException: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:111)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:290)
at com.opencsv.bean.AbstractBeanField.setFieldValue(AbstractBeanField.java:182)
at com.opencsv.bean.AbstractMappingStrategy.setFieldValue(AbstractMappingStrategy.java:607)
at com.opencsv.bean.AbstractMappingStrategy.populateNewBean(AbstractMappingStrategy.java:330)
at com.opencsv.bean.concurrent.ProcessCsvLine.processLine(ProcessCsvLine.java:131)
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:87)
... 3 more
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.opencsv.bean.FieldAccess.lambda$determineAssignmentMethod$3(FieldAccess.java:79)
at com.opencsv.bean.FieldAccess.setField(FieldAccess.java:115)
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:286)
... 8 more
Caused by: com.opencsv.exceptions.CsvValidationException: 'Contact First Name' must be between 3-8 characters long
at org.lotia.example.entity.Contact.setContactFirstName(Contact.java:23)
... 15 more
java.lang.RuntimeException: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.concurrent.IntolerantThreadPoolExecutor.checkExceptions(IntolerantThreadPoolExecutor.java:253)
at com.opencsv.bean.concurrent.LineExecutor.checkExceptions(LineExecutor.java:67)
at com.opencsv.bean.concurrent.IntolerantThreadPoolExecutor.areMoreResultsAvailable(IntolerantThreadPoolExecutor.java:303)
at com.opencsv.bean.concurrent.IntolerantThreadPoolExecutor.tryAdvance(IntolerantThreadPoolExecutor.java:313)
at com.opencsv.bean.concurrent.LineExecutor.tryAdvance(LineExecutor.java:24)
at java.base/java.util.Spliterator.forEachRemaining(Spliterator.java:326)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
at com.opencsv.bean.CsvToBean.parse(CsvToBean.java:117)
at org.lotia.example.ContactTest.test(ContactTest.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: com.opencsv.exceptions.CsvBeanIntrospectionException: An introspection error was thrown while attempting to manipulate property contactFirstName of bean org.lotia.example.entity.Contact.
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:290)
at com.opencsv.bean.AbstractBeanField.setFieldValue(AbstractBeanField.java:182)
at com.opencsv.bean.AbstractMappingStrategy.setFieldValue(AbstractMappingStrategy.java:607)
at com.opencsv.bean.AbstractMappingStrategy.populateNewBean(AbstractMappingStrategy.java:330)
at com.opencsv.bean.concurrent.ProcessCsvLine.processLine(ProcessCsvLine.java:131)
at com.opencsv.bean.concurrent.ProcessCsvLine.run(ProcessCsvLine.java:87)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.opencsv.bean.FieldAccess.lambda$determineAssignmentMethod$3(FieldAccess.java:79)
at com.opencsv.bean.FieldAccess.setField(FieldAccess.java:115)
at com.opencsv.bean.AbstractBeanField.assignValueToField(AbstractBeanField.java:286)
... 8 more
Caused by: com.opencsv.exceptions.CsvValidationException: 'Contact First Name' must be between 3-8 characters long
at org.lotia.example.entity.Contact.setContactFirstName(Contact.java:23)
... 15 more
Process finished with exit code 255
最佳答案
如果您不想添加另一个库,您还可以创建一个自定义 validator 来代替 MustMatchRegexExpression:
public class MySpecialMustMatchRegexExpression implements StringValidator {
private String regex = "";
public MustMatchRegexExpression() {
this.regex = "";
}
@Override
public boolean isValid(String value) {
if (regex.isEmpty()) {
return true;
}
return value.matches(regex);
}
@Override
public void validate(String value, BeanField field) throws CsvValidationException {
if (!isValid(value)) {
throw new CsvValidationException(String.format(ResourceBundle.getBundle("mustMatchRegex", field.getErrorLocale())
.getString("validator.regex.mismatch"), field.getDeclaredAnnotations[1], value, regex));
}
}
@Override
public void setParameterString(String value) {
if (value != null && !value.isEmpty()) {
regex = value;
}
}
}
并在您的预赋值 validator 中使用它:
@PreAssignmentValidator(validator = MySpecialMustMatchRegexExpression.class, paramString = "^[A-Za-z]{3,8}$")
@CsvBindByName(column = "Contact First Name", required = true)
private String contactFirstName;
关于java - Opencsv:使用@PreAssignmentValidator 时允许更多自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66285717/
我使用了 opencsv 的“http://opencsv.sourceforge.net/#maven-integration ” maven 依赖项,如下所示: net.sf.openc
我正在尝试使用 HeaderColumnNameMappingStrategy 使用 opencsv 读取 csv 文件。 Opencsv 每次都将我的第一列 csv 填充为 null。 这是我的代码
使用 OpenCSV 库,调用 StatefulBeanToCsv.write()我的空值被包裹在引号中。 例子: String[] columns = new String[] { "Col
我正在使用 AndroidStudio,我的应用程序必须读取如下所示的 CSV 文件: "Anmeldung";"1576017126809898";"1547126680978123";"";"";
在我的主课 public static void main(String[] args) { CSVWriter writer = new CSVWriter(new Fi
我使用openCSV导入文件,但通常它只读取文件的一部分。它处理包含约 5k 行的文件,但通常 20k 对他来说是个问题(即使是 1 列的 CSV)。 当我尝试使用 BufferedReader 而不
我试图使用 openCSV java 库在 csv 文件中写入一些公式数据,但它只写入每个单元格中大约 90% 的字符串。是否有任何已知问题可能导致此行为? public static void ma
我正在使用 opencsv 2.3,它似乎没有像我预期的那样处理转义字符。我需要能够处理不使用引号字符的 CSV 文件中的转义分隔符。 示例测试代码: CSVReader reader = new C
我试图从分号分隔的文件中的倒数第二行和第三列获取值。我无法坐下来获取倒数第二行和第三列的值。 我一直在寻找一种方法来实现这一目标,但没有结果。如果有人能用一个例子为我指明正确的方向,我将不胜感激。 这
我正在尝试使用 opencsv 解析 csv 文件。文件中的最后一列有一个参数,实际上是 json。该 json 包含在“”中。问题是 opencsv 正在从 json 中删除一些 "导致我的代码中断
我使用 open csv 来读取只有 2 列的 CSV,例如: "valueA1","valueB of A1" ,"valueB of A1" ,"valueB of A1" ,"valueB of
我陷入了必须读取两个不同的 csv 文件并将它们存储在单个表中的情况。 CSV 文件1: salary,date,user 121,2016-08-01,admin 121,2016-08-01,ad
我有一个 CSV 文件,其中引号内有定界符或未闭合的引号,如何让 CSVReader 忽略引号内的引号和定界符。例如: 123|Bhajji|Maga|39|"I said Hey|" I am "5
我使用的是 opencsv 3.0 版本。由于某种原因,它没有将记录写出到 CSV 文件中。它适用于 2.3 版。但是,我想使用 CSVIterator 类。感谢您的帮助。 public void
我正在尝试使用 opencsv 解析一些公共(public)数据(3.10 版)。下面是获取 CSV 并将记录映射到 POJO 列表的代码片段: URL permitsURL = new URL("h
好的,我有一个 csv 文件: Summary heading1,heading2,heading3 value1,value2,value2 value1,value2,va
我需要有关在 Java 中解析 CSV 数据时遇到的问题的建议。 我有一个 CSV 文件,其中包含以下格式的数据 name, gender, address_first_line, address_s
我编写了一个脚本,使用 tokenize 在 groovy 中解析 .csv 文件,但最终没有完全满足我的需要,我正在尝试使用 openCSV 库,但我不确定如何解析各个列。这是到目前为止我的代码:
我正在使用 openCSV 的 CsvToBean 类。该 bean 具有日期字段。 @CsvDate(value = "yyyy-MM-dd") @CsvBindByPosition(positio
我有以下 CSV 文件, "id","Description","vale" 1,New"Account","val1" 我无法使用 OpenCSV 读取上述 CSV 文件。它无法读取 New"Acc
我是一名优秀的程序员,十分优秀!