在使用Apache commons-csv进行csv文件读写操作时,如果要在字段中使用#(双引号)字符,需要将其进行转义,否则该字符会被解释为表示引用字段的起止的特殊字符。
可以使用\来转义#字符,示例代码如下:
CSVFormat format = CSVFormat.DEFAULT;
format = format.withEscape('\\');
String str = "1,\"Hello, \"\"Apache commons-csv\"\"!\"#456";
StringReader reader = new StringReader(str);
Iterable records = format.parse(reader);
for (CSVRecord record : records) {
for (int i = 0; i < record.size(); i++) {
System.out.print(record.get(i) + " ");
}
}
在以上代码中,我们通过format.withEscape('\')将\字符设置为转义字符,然后在读取含有#字符的字符串时,将#前面加上\进行转义,正确输出包含#字符的字段。