How to remove double quotes when reading CSV

public class CSVTeast { public static void main(String[] args) { CSVTeast obj = new CSVTeast(); obj.run(); } public void run() { String csvFile = "D:\\text.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = "~"; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { // use comma as separator String[] csvRead = line.split(cvsSplitBy); System.out.println("Value [date= " + csvRead[5] + " , name=" + csvRead[9]+"]"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("Done"); } } 

Output

 Value [date= "POLICY_CHANGE_EFFECTIVE_DATE" , name="AGENCY_NAME"] Value [date= "2014-04-01" , name="USI INSURANCE SERVICES]--this value stated with double qoutes but not end with same . 

Expected Result

 Value [date= POLICY_CHANGE_EFFECTIVE_DATE , name=AGENCY_NAME] Value [date= 2014-04-01 , name=USI INSURANCE SERVICES] 
+6
source share
4 answers

You can try passing a value using the String.replace () method.

So your code will look like this:

 public class CSVTeast { public static void main(String[] args) { CSVTeast obj = new CSVTeast(); obj.run(); } public void run() { String csvFile = "D:\\text.csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = "~"; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] csvRead = line.split(cvsSplitBy); System.out.println("Value [date= " + csvRead[5].replace("\"","") + " , name=" + csvRead[9].replace("\"","")+"]"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("Done"); } } 
+5
source

There's a nice CSV Reader for Java that will handle a mess of this for you, http://opencsv.sourceforge.net/

It has a maven package if your project is maven, otherwise you can load the JAR there.

+2
source

If qoutemarks are at the beginning of each CSV line, you can do:

 csvRead[5].substring(1, csvRead[5].length()-1) 

This will delete the first and last characters of this particular line. Then you need to save the results somewhere or print.

+1
source

It is also important to check whether the string begins with a double quote, otherwise the code will begin to delete the first character of the CSV value. I do this in my code in one of my applications, where my CSV value goes to rowData [1], which sometimes has double quotes, and sometimes not, depending on the number of words in the String value.

 String item = (String.valueOf(rowData[1].charAt(0)).equals("\"") ? rowData[1].substring(1, rowData[1].length() - 1) : rowData[1]); 
+1
source

Source: https://habr.com/ru/post/970441/


All Articles