how to remove double quotes while reading CSV
Solution 1
You can try passing the value through the String.replace() method.
So your code would be:
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");
}
}
Solution 2
There's a nice CSV Reader for Java that will handle the mess of this for you, http://opencsv.sourceforge.net/
It has a maven package if your project is maven, else you can download the JARs there.
Solution 3
If the qoutemarks are at the beginning of every CSV line, you can do:
csvRead[5].substring(1, csvRead[5].length()-1)
That will remove the first and last character of that particular string. You then need to store the results somewhere or print it out.
Solution 4
It is also important to check if the String starts with a double quote, otherwise the code will start deleting the first character of the CSV value. I do this in my code in one of my apps, where my CSV value is coming in rowData[1] which sometimes have double quotes and sometimes it doesn't, depending upon the number of words in the value String.
String item = (String.valueOf(rowData[1].charAt(0)).equals("\"") ? rowData[1].substring(1, rowData[1].length() - 1) : rowData[1]);
Anandv
Updated on June 15, 2022Comments
-
Anandv about 2 years
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 is
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 output
Value [date= POLICY_CHANGE_EFFECTIVE_DATE , name=AGENCY_NAME] Value [date= 2014-04-01 , name=USI INSURANCE SERVICES]