'Spring Batch FlatFileItemWriter - output customization
I would have the need to produce a CSV File with the following requirements:
- Every field is surrounded by double quotes
- Double quotes are escaped with backslash
- Backslash is escaped with backslash
Input:
- Field1
- Field2With\Backslash"DoubleQuotes"And|Pipe
- Field3
Expected output:
"Field1"|"Field2With\\Backslash\"DoubleQuotes\"And|Pipe"|"Field3"
Is it possible to obtain such an output?
Solution 1:[1]
Best solution is to implement quoting and escaping in a subclass of DelimitedLineAggregator.
Solution 2:[2]
Basically, you just want to process your fields before writing it. You could do it with these 2 ways
Let's say this method processes your field
public String escape(String str) {
str = "\"" + str + "\"";
str = str.replace("|", "\\|");
str = str.replace("\\", "\\\\");
return str;
}
1 - Process it during processor - preferred
@Override
public A process(B b) throws Exception {
A a = new A();
//Process b to a...
a.setField1(escape(a.getField1)); //For each fields
return a;
}
2 - Process it before writing in custom Writer
public class EscapeFlatFileItemWriter<A> extends FlatFileItemWriter<A> {
@Override
public void write(List<? extends A> items) throws Exception {
for (A a : items) {
a.setField1(escape(a.getField1)); //For each fields
}
super.write(items);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Giulio Pulina |
Solution 2 | ACH |