[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2174
  • Last Modified:

opencsv CSVReader does not read \ (backslash)

I am reading CSV file using the following code. I use OpenCSV library.

csvReaderList.add(new CSVReader(new FileReader(csvFileNames.get(2))));
while ((nextLineCsv1 = csvReaderList.get(0).readNext()) != null&&(nextLineCsv2= csvReaderList.get(1).readNext()) != null&&(nextLineCsv3 = csvReaderList.get(2).readNext()) != null) {
		    	ArrayList<String[]> rowFromAllThreeCsv=new ArrayList<String[]>();

Open in new window

Below you can see the exact csv file line. The first one succeeds it has \ followed by space. The next one fails it has only \. When read the first one returns an array of 12 cells and the next one has only 6.

The below works
"25-Jan-2008 08:46:00","datamirror","","50545","#PGAAGIN    ","1020360224","\                             ","0","TRSYS","CMPLACTS    ","",""

The below fails
"25-Jan-2008 08:46:00","datamirror","","50545","#PGAAGIN","1020360224","\","0","TRSYS","CMPLACTS","",""

I think i need to initilise the CSVReader wih the right constructor. Please help.
1 Solution
PearlJamFanaticAuthor Commented:
The problem could be with special characters (something that looks like space character). The \ appears in the line that works. Its \ followed by the special characters that didn't work.
Jim CakalicSenior Developer/ArchitectCommented:
The default escape character for quotes (so it can appear in the data) is the backslash. In the event that you want backslash to be a valid data character there is a constructor that lets you modify which character is the escape:
CSVReader(Reader reader, char separator, char quotechar, char escape)
You can use CSVParser.DEFAULT_SEPARATOR and CSVParser.DEFAULT_QUOTE_CHARACTER as the values for the separator and quotechar arguments. Use whatever character you must then for the escape.

If you're data wasn't created with the concept of an escape character then an ugly alternative would be to pre-process the input and either remove or escape the escape character.


Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now