1

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?

EDIT

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.

4

1 回答 1

2

解决方案分为两部分:

首先,请确保您使用的是 2.2.3 版本,因为它刚刚发布并进行了调整,以正确捕获未转义的引号转义字符,这是您的情况:

这里/没有转义:

"Alex ,/,awesome/,"

2.2.3 之前的版本会这样:

"Alex ,//,awesome//,"

其次,当把它写回输出时,你不会想写转义转义,即,给定"Alex ,/,awesome/," 你想要得到的字符串:

"Alex ,/,awesome/,"

而不是默认情况下会执行的操作:

"Alex ,//,awesome//,"

在 CsvWriterSettings 上,执行以下操作:

settings.getFormat().setCharToEscapeQuoteEscaping('\0');

它不会尝试转义引号转义字符。

希望能帮助到你

于 2016-10-30T02:39:58.007 回答