I am using univocity to parse files to beans, perform some magic on the objects, and afterwards write the beans back to a file. The code snippet that duplicates my problem:
public class Sample {
public static void main(String[] args) throws IOException {
BeanListProcessor<Person> rowProcessor = new BeanListProcessor<Person>(Person.class);
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setProcessor(rowProcessor);
parserSettings.getFormat().setDelimiter(',');
parserSettings.getFormat().setQuote('"');
parserSettings.getFormat().setQuoteEscape('/');
CsvParser parser = new CsvParser(parserSettings);
parser.parse(new FileReader("src/main/resources/person.csv"));
List<Person> beans = rowProcessor.getBeans();
Writer outputWriter = new FileWriter("src/main/resources/personOut.csv", true);
CsvWriterSettings settings = new CsvWriterSettings();
settings.getFormat().setDelimiter(',');
settings.getFormat().setQuote('"');
settings.getFormat().setQuoteEscape('/');
settings.setRowWriterProcessor(new BeanWriterProcessor<Person>(Person.class));
CsvWriter writer = new CsvWriter(outputWriter, settings);
for (Person person : beans) {
writer.processRecord(person);
}
writer.close();
}
}
Bean class (getters and setters ommited):
public class Person {
@Parsed(index = 0)
private int id;
@Parsed(index = 1)
private String firstName;
@Parsed(index = 2)
private String lastName;
}
And the file content (input):
1,"Alex ,/,awesome/,",chan
2,"Peter ,boring",pitt
The file is not under my control as it is being provided by an external party. After the application performs operation on the objects (not included in the code snippet), I need to return the file to the external party with exactly the same settings.
Desired file output content:
1,"Alex ,/,awesome/,",chan
2,"Peter ,boring",pitt
However I am getting:
1,"Alex ,,awesome,",chan
2,"Peter ,boring",pitt
Is there a way to include the actual used quote escape character when writing the beans back to a file?
I have tried using settings.setQuoteAllFields(true);
on the writer and all combinations of
parserSettings.setKeepQuotes(true);
parserSettings.setKeepEscapeSequences(true);
on the CsvParserSettings, but none seem to give me the result I am looking for.
The solution for this is divided in two parts:
First, please make sure you use version 2.2.3, as it's been just released with an adjustment to properly capture the quote escape character if it's not been escaped, which is your case:
Here the /
is not escaped:
"Alex ,/,awesome/,"
Versions prior to 2.2.3 would expect this:
"Alex ,//,awesome//,"
Second, when writing this back to the output, you won't want to write the escape escape, i.e., given the string "Alex ,/,awesome/,"
you want to get:
"Alex ,/,awesome/,"
Instead of what it will do by default:
"Alex ,//,awesome//,"
On the CsvWriterSettings, do this:
settings.getFormat().setCharToEscapeQuoteEscaping('\0');
And it will not try to escape the quote escape character.
Hope it helps