-1

J have CSV File first row is like this :

LOC;11000;"Autorisation "valide";10;;

When i try to read it with CSVReader i have only this:

LOC;11000

I know the problem is the double quote, how i can do to remove all double quote on my CSV ?

I try replace method is dosnt work.

My code is:

while ((line = reader.readNext()) != null) {

    for(int i = 0; i<line.length; i++) {

        if (line[i].contains("\"")){

            line[i] = line[i].replace("\"", ""); // same result with replaceAll method
        }

        System.out.print(line[i]+" ");
    }
}

Thank you.

maa aam
  • 1
  • 3
  • 3
    You're only trying to replace the quotes if there is a "\n" in the entry at index i, which (as shown by your CSV example) does not contain any quotations. To put it another way, you are trying to do something like "\n".replace("\"","") which effectively does nothing. – Brendan Lesniak Oct 04 '21 at 16:41
  • i mean if (line[i].contains("\"")) – maa aam Oct 04 '21 at 16:46
  • yes is a array : String line[]; i cant do line = line.replace("\"", ""); – maa aam Oct 04 '21 at 16:59

1 Answers1

0

As mentioned by Brendan, the line " if (line[i].contains(""")){" is redundant. The find and replace method will scan the text anyways, you don't need to do it twice.

Your replace statements works, I tried it, but that is not the issue:

jshell> var text = "LOC;11000;\"Autorisation \"valide\";10;;";
text ==> "LOC;11000;\"Autorisation \"valide\";10;;"

jshell> text.contains("\"")
$2 ==> true

jshell> text.replace("\"","");
$3 ==> "LOC;11000;Autorisation valide;10;;"

Notice that line is not a list/iteratable, its a string, so you can just replace it on line.

while ((line = reader.readNext()) != null) {
     line = line.replaceAll("[\"\\\\]","");  
     System.out.print(line);
}

enter image description here

Omeri
  • 187
  • 2
  • 16
  • i dont have var text = "LOC;11000;\"Autorisation \"valide\";10;;"; but i have var text = "LOC;11000;\"Autorisation "valide\";10;;"; – maa aam Oct 04 '21 at 17:07
  • 1
    I'm assuming from the csvreader tag that the readNext method is from CSVReader [reader.readNext()](http://opencsv.sourceforge.net/apidocs/com/opencsv/CSVReader.html#readNext--) which has a method signature of `public String[] readNext() throws IOException, CsvValidationException`. – Matthew0898 Oct 04 '21 at 17:26
  • I updated it with a regex replace to work for that condition as well, @maa_amm. Good luck with your project. – Omeri Oct 04 '21 at 17:29