OpenCsv csvwriter adding leading space in each row?

117 Views Asked by At

I am using openCsv to read strings from list and write in csv file. This file will be uploaded in a website which validates the string(a combination of letters and numbers seaprated by ~) present in files and does not accept any spaces or other characters.

When the file is uploaded the website is saying it has invalid entries.While the data is written in the .csv, I am seeing a extra character added before each column. I initially thought it is a leading space but I am not able to see any. Just in case I tried hitting blankspace before each value in row and tried uploading the file. It is getting uploaded.

So what should I do to not add that leading character? These files will be used in automation process so I won't be able to open amd edit every time.

I tried using strip() and trim() to the string before adding it in an array and then passing it to writenext():

FileWriter fw=new FileWriter("check.csv");
String setup="12348448~RR";
String arr[]=new String[1];
arr[0]=setup.strip();
CsvWriter csvw=new CsvWriter(fw);
csvw.writeNext(arr);

But still the the text inside is shown as invalid but once I hit the backspace in front of the data in each row and upload the same file, it is getting uploaded.

What is the leading character used here? Is there any way to not open and edit the file every time after writing? Any suggestions even on using other csv libraries would also be useful.

Edit: I am using Java SE 11 in Windows. I am using openCsv version 4.1.

1

There are 1 best solutions below

0
On BEST ANSWER

If you look at the source code of the latest version of OpenCSV, you will see that writeNext(array) calls writeNext(array, true) where the 2nd argument is applyQuotesToAll. That argument tells the writer to output each value in quotes, irrespective of whether quoting is required based on the value's characters.

The same applies to the older version that you are using.

Based on this, I conclude that:

  1. You are generating a CSV file where the values are all quoted.

  2. The unexpected character at the start of the first line would therefore be a double quote; i.e. the writer's default quoting character.

    I don't know why you couldn't see the character, but it may be that the website's error message is tricky to read. For example, if it enclosed the unexpected character in quotes, you might misinterpret '"' or """.

  3. The fix would be to use writeNext(array, false) instead of writeNext(array).

The source code link for CSVWriter in OpenCSV 4.1 is here and the relevant code is at line 368.