记录一次Apache Commons CSV库中封装的令牌和定界符之间的字符无效

 

使用Apache Commons CSV库解析CSV文件时出现以下错误。

java.lang.IllegalStateException: IOException reading next record: java.io.IOException: (line 1) invalid char between encapsulated token and delimiter

at org.apache.commons.csv.Lexer.parseEncapsulatedToken(Lexer.java:<span style="color:var(--highlight-namespace)">275</span>)
at org.apache.commons.csv.Lexer.nextToken(Lexer.java:<span style="color:var(--highlight-namespace)">152</span>)
at org.apache.commons.csv.CSVParser.nextRecord(CSVParser.java:<span style="color:var(--highlight-namespace)">450</span>)
at org.apache.commons.csv.CSVParser.getRecords(CSVParser.java:<span style="color:var(--highlight-namespace)">327</span>)
at parse.csv.file.CSVFileParser.main(CSVFileParser.java:<span style="color:var(--highlight-namespace)">29</span>)</code></span></span>

应用的解决方案为 CSVFormat csvFileFormat = CSVFormat.DEFAULT.withQuote(null);

CSVFormat format = CSVFormat.DEFAULT.withQuote(null);
我的完整代码为:
String path = "你的csv文件地址";
CSVFormat format = CSVFormat.DEFAULT.withQuote(null);
InputStreamReader inputStreamReader = null;
CSVParser parser = null;

FileInputStream  is = null;
File file = new File(path);
is = new FileInputStream (file);
inputStreamReader = new InputStreamReader(is,"UTF-8");
            //创建CSVParser对象
parser = new CSVParser(inputStreamReader, format);

原因是:

CSV文件中的该行在您的一个单元格与行尾,文件末尾或下一个单元格之间包含无效字符。造成这种情况的一个非常常见的原因是无法转义封装字符(用于“包装”每个单元格的字符,因此CSV知道单元格(令牌)的开始和结束位置。

我的CSV文件具有如下属性: “带有嵌套“ quote”的属性”

由于属性中的嵌套引号导致解析器失败

猜你喜欢

转载自blog.csdn.net/Dengrz/article/details/110529822