I have a requirement to parse external CSV files and read their name attributes. I am using opencsv library to achieve this, please find the test code below. It works pretty well with valid CSV files, however, if one of the rows is invalid, there is no way to handle that error. I shared an example CSV below with an error case, inside which the escaped double quote is causing the problem in java. Could we somehow parse this inline or at the file level and replace \"
with "
.
@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));
}
}
}
}
ERROR.csv
id,name,address,phone
"1","Bob","New Jersey","9999999999"
"2","Smith","Sydney ///\","9999999999"
Note: When we open this csv file in the excel app, then it renders perfectly, so is it only in the java world that is treating it erroneously, because a double quote has been escaped with the preceding backslash (
\"
)?