如何解析含反斜杠的CSV?OpenCSV转义双引号异常处理方案
问题:OpenCSV解析含异常转义双引号的CSV文件失败
我用OpenCSV解析外部CSV文件读取name属性,合法CSV文件能正常处理,但遇到含异常转义的行时会报错。问题出在CSV中的\"转义格式在Java环境下无法被OpenCSV正确识别,想问能不能在解析过程或文件预处理阶段把\"替换为"?
测试代码
@Test public void csvTest() throws IOException { String fileName = "ERROR.csv"; File file = new File("D:\\csvFiles\\" + fileName); if (file.exists()) { CSVReader csvReader = new CSVReader(new FileReader("D:\\csvFiles\\" + fileName)); String[] nextLine; int row = 0; while ((nextLine = csvReader.readNext()) != null) { row++; if (nextLine.length > 0) { System.out.println("ROW: " + row + " " + String.join(",", nextLine)); } } } }
错误示例CSV(ERROR.csv)
id,name,address,phone "1","Bob","New Jersey","9999999999" "2","Smith","Sydney ///\"","9999999999"
注意:用Excel打开该CSV文件显示正常,是不是只有Java环境会因前置反斜杠转义双引号导致处理错误?
解决方法
1. 预处理文件替换异常转义符
在读入OpenCSV前,先将文件中的\"替换为CSV标准的双引号转义格式"",或者直接替换为"(根据业务需求选择):
@Test public void csvTest() throws IOException { String fileName = "ERROR.csv"; File inputFile = new File("D:\\csvFiles\\" + fileName); if (!inputFile.exists()) return; // 创建临时文件存储预处理后的内容 Path tempPath = Files.createTempFile("temp_csv", ".csv"); try (BufferedReader reader = Files.newBufferedReader(inputFile.toPath()); BufferedWriter writer = Files.newBufferedWriter(tempPath)) { String line; while ((line = reader.readLine()) != null) { // 把非标准的\"替换为CSV标准的"",也可根据需求替换为" String processedLine = line.replace("\\\"", "\"\""); writer.write(processedLine); writer.newLine(); } } // 用OpenCSV读取预处理后的临时文件 try (CSVReader csvReader = new CSVReader(new FileReader(tempPath.toFile()))) { String[] nextLine; int row = 0; while ((nextLine = csvReader.readNext()) != null) { row++; if (nextLine.length > 0) { System.out.println("ROW: " + row + " " + String.join(",", nextLine)); } } } finally { // 清理临时文件 Files.deleteIfExists(tempPath); } }
2. 配置OpenCSV使用自定义转义规则
OpenCSV默认遵循RFC4180标准(用""转义双引号),但可以通过自定义CSVParser适配Java风格的\"转义:
@Test public void csvTest() throws IOException { String fileName = "ERROR.csv"; File file = new File("D:\\csvFiles\\" + fileName); if (!file.exists()) return; // 自定义解析器,将反斜杠设为转义符 CSVParser parser = new CSVParserBuilder() .withSeparator(',') .withQuoteChar('"') .withEscapeChar('\\') .build(); try (CSVReader csvReader = new CSVReaderBuilder(new FileReader(file)) .withCSVParser(parser) .build()) { String[] nextLine; int row = 0; while ((nextLine = csvReader.readNext()) != null) { row++; if (nextLine.length > 0) { System.out.println("ROW: " + row + " " + String.join(",", nextLine)); } } } }
关于Excel正常打开的原因
Excel读取CSV时兼容多种非标准转义方式,包括Java风格的\";而OpenCSV默认严格遵循RFC4180标准,因此只有Java环境会出现这个兼容性问题。
内容的提问来源于stack exchange,提问作者JavaCodeNet
相关产品推荐
相关产品推荐

