英文:
How to tell Apache Camel BindyCsvDataFormat to ignore blank lines?
问题
我有一个以几行空白结尾的CSV文件。我想使用BindyCsvDataFormat将每一行非空的数据解析为Java对象,方法如下:
//在我的RouteBuilder类中
from("{{route.from}}")
.unmarshal(new BindyCsvDataFormat(MyClass.class).)
@CsvRecord(separator = ",", skipField = true, skipFirstLine = true, generateHeaderColumns = true, allowEmptyStream = true)
@Data
public class MyClass {
@DataField(pos = 1, required = true)
@NotEmpty
private String myString;
@DataField(pos = 2, required = true, pattern = "M/d/yyyy")
@NotNull
private LocalDate myDate;
@DataField(pos = 3, required = false, pattern = "M/d/yyyy")
private LocalDate notRequiredDate;
}
当Camel尝试解析空行(仅包含回车和换行符)时,会抛出以下异常:
java.lang.IllegalArgumentException: The mandatory field defined at the position 1 is empty for the line: 5
你想要告诉Apache Camel忽略空行,你可以在MyClass
类的@CsvRecord
注解中添加skipEmptyLines = true
属性,如下所示:
@CsvRecord(separator = ",", skipField = true, skipFirstLine = true, generateHeaderColumns = true, allowEmptyStream = true, skipEmptyLines = true)
这将告诉Camel在解析时跳过空行。
英文:
I have a CSV file that ends with a few empty lines. I would like to unmarshal each non-empty line into a Java object using BindyCsvDataFormat as follows:
//within my RouteBuilder class
from("{{route.from}}")
.unmarshal(new BindyCsvDataFormat(MyClass.class).)
@CsvRecord(separator = ",", skipField = true, skipFirstLine = true, generateHeaderColumns = true, allowEmptyStream = true)
@Data
public class MyClass {
@DataField(pos = 1, required = true)
@NotEmpty
private String myString;
@DataField(pos = 2, required = true, pattern = "M/d/yyyy")
@NotNull
private LocalDate myDate;
@DataField(pos = 3, required = false, pattern = "M/d/yyyy")
private LocalDate notRequiredDate;
}
When Camel attempts to unmarshal an empty line (containing only a carriage return followed by a line feed), it throws:
java.lang.IllegalArgumentException: The mandatory field defined at the position 1 is empty for the line: 5
How do I tell Apache Camel to ignore empty lines?
答案1
得分: 2
可能的替代方法是在反序列化之前过滤掉空行。这可以很容易地使用filter
EIP和simple
语言来实现:
from("direct:demo")
.split(body().tokenize("\n"))
.streaming()
.filter(simple("${body.length} > 0"))
.unmarshal(new BindyCsvDataFormat(MyClass.class))
英文:
A possible alternative could be to filter out empty lines before unmarshalling.
This can be easily done using the filter
EIP and simple
language:
from("direct:demo")
.split(body().tokenize("\n"))
.streaming()
.filter( simple("${body.length} > 0") )
.unmarshal(new BindyCsvDataFormat(MyClass.class))
答案2
得分: 1
我不认为这在Bindy中是可能的。一个潜在的解决方法是根据换行符将文件拆分成多行,然后根据行是否为空,有条件地通过Bindy进行逐行解析。
英文:
I don't see that this is possible with Bindy. A potential workaround would be to split the file on line endings, then conditionally unmarshal individual lines through Bindy based on whether or not the line is empty.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论