San*_*har 27 java apache-commons apache-commons-csv
使用Apache Commons CSV库解析CSV文件时出现以下错误.
Exception in thread "main" java.io.IOException: (line 2) invalid char between encapsulated token and delimiter
at org.apache.commons.csv.Lexer.parseEncapsulatedToken(Lexer.java:275)
at org.apache.commons.csv.Lexer.nextToken(Lexer.java:152)
at org.apache.commons.csv.CSVParser.nextRecord(CSVParser.java:450)
at org.apache.commons.csv.CSVParser.getRecords(CSVParser.java:327)
at parse.csv.file.CSVFileParser.main(CSVFileParser.java:29)
Run Code Online (Sandbox Code Playgroud)
这个错误是什么意思?
Ana*_*and 36
当我们在数据中嵌入报价时,我们遇到了这个问题.
0,"020"1,"BS:5252525 ORDER:99999"4
Run Code Online (Sandbox Code Playgroud)
应用解决方案是 CSVFormat csvFileFormat = CSVFormat.DEFAULT.withQuote(null);
@Cuga小费帮我们解决了.谢谢@Cuga
完整的代码是
public static void main(String[] args) throws IOException {
FileReader fileReader = null;
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withQuote(null);
String fileName = "test.csv";
fileReader = new FileReader(fileName);
CSVParser csvFileParser = new CSVParser(fileReader, csvFileFormat);
List<CSVRecord> csvRecords = csvFileParser.getRecords();
for (CSVRecord csvRecord : csvRecords) {
System.out.println(csvRecord);
}
csvFileParser.close();
}
Run Code Online (Sandbox Code Playgroud)
结果是
CSVRecord [comment=null, mapping=null, recordNumber=1, values=[0, "020"1, "BS:5252525 ORDER:99999"4]]
Run Code Online (Sandbox Code Playgroud)
CSV文件中的该行包含一个单元格与行尾,文件结尾或下一个单元格之间的无效字符.造成这种情况的一个常见原因是无法转义封装字符(用于"封装"每个单元格的字符,因此CSV知道单元格(标记)的开始和结束位置.
我找到了问题的解决方案.我的一个CSV文件具有如下属性: "带有嵌套的属性"quote""
由于属性中的嵌套引号,解析器失败.
为避免上述问题,请按如下方式转义嵌套引号: "with embedded with nest""""quote"""""
这是解决问题的一种方法.