0

I am working on a java project. I have to retain a comma separator from my parsed string "," and still should be able to write into csv file. currently my csv file values are separated with comma (",") in it . because of this , if I have comma in a string its divided into two string on csv

ex:

input string : "Animal","Stand","Earth","owner,jeff"

my current output : (which is incorrect )

enter image description here

Expected output :

enter image description here

I have the logic in place for writing things into csv , I just need the string to be manipulated in a such way it should in corporate the ",". how to achieve this ?

here is my code:

private static void Addrow(String Animals, String Posture, String planet,String owner) throws IOException {
        String csv_write = csv_file_to_write;
        CSVWriter writer = new CSVWriter(new FileWriter(csv_write , true));

            String [] record = (Animals+","+Posture+","+planet+","+owner).split(",");

        writer.writeNext(record);

        writer.close();

    }
Divakar R
  • 773
  • 1
  • 8
  • 36
  • 1
    Add the code that you have tried. – Java-Dev Nov 11 '20 at 08:51
  • @javaDev I have updated my code , plz refer – Divakar R Nov 11 '20 at 09:01
  • Does this solve your problem? [Is there a way to include commas in CSV columns without breaking the formatting?](https://stackoverflow.com/q/4617935/7722745) – sn- Nov 11 '20 at 09:22
  • @asn21 i have read that post there they talk about enclosing the string with " " but in my case entire string looks something like this `"Animal","'Stand'","Earth","Owner","Jeff" ` how to enclose this with " "? – Divakar R Nov 11 '20 at 09:25
  • I was able to remove the quotes by CSVWriter.NO_QUOTE_CHARACTER but now i am not able to add quotes around the exact string i want – Divakar R Nov 11 '20 at 09:45

1 Answers1

1

One way to tackle that would be to split it at \",\" and for the first entry remove the " at the beginning and for the last entry remove the " at the end. You will then be left with the list of strings Animal, Stand, Earth, Owner,Jeff and so on...