1

I know there is already a question related to this: How to keep quotes when parsing csv file? (But it's for C#)

Let's say I have a csv with values e.g:

12312414-DEF_234, "34-DE, 234-EG, 36354-EJ", 23
...

When I parse it with OpenCSV, it doesn't keep the quotes.

CSVReader reader = new CSVReader(new FileReader("../path.csv"), ',', '\"');
List<String[]> list = reader.readAll();

String[][] csvArray = new String[list.size()][];
csvArray = list.toArray(csvArray);

So, after I store all of the values into an array, when I try to print out the values (for checking), the quotes are not there.

...
System.out.println(csvArray[i][j]);
// output below
// 34-DE, 234-EG, 36354-EJ

How can I keep the quotes? The reason is because I am going to be changing some values, and need to re-output it back into a csv.

Community
  • 1
  • 1

2 Answers2

3

The CSVReader has to parse and remove the quotes, otherwise you wouldn't get one value 34-DE, 234-EG, 36354-EJ, but three values "34-DE, 234-EG and 36354-EJ". So it's OK that the quotes are being removed.

The CSVWriter should add them again for every value that needs quoting.

Have you tried to write the array back into a CSV? The value 34-DE, 234-EG, 36354-EJ - actually any value that contains a comma - should be quoted.

Kris Scheibe
  • 361
  • 2
  • 5
  • Yes the CSVWriter does add the quotes to all values separated by a comma. But ideally, I want to keep it in the same format as when I got it.. Meaning only that value in the second column - or would it not matter and the file can be read the same way with all wrapped in quotes? –  Jun 26 '14 at 02:15
  • @B.V since CSVWriter adds them back, I don't see why it would matter – eis Jun 26 '14 at 05:43
0
public static void readCSV(){
    String csvFile = "input.csv";
    BufferedReader br = null;
    String line = "";
    String splitter = ",";

    try {

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {

                // use comma as separator
            String[] words = line.split(splitter);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Maverick
  • 91
  • 3
  • 10