How can I read comma separated values from a text file in Java?
You may use the String.split()
method:
String[] tokens = str.split(",");
After that, use Double.parseDouble()
method to parse the string value to a double.
double latitude = Double.parseDouble(tokens[0]);
double longitude = Double.parseDouble(tokens[1]);
Similar parse methods exist in the other wrapper classes as well - Integer
, Boolean
, etc.
Use OpenCSV for reliability. Split should never be used for these kind of things. Here's a snippet from a program of my own, it's pretty straightforward. I check if a delimiter character was specified and use this one if it is, if not I use the default in OpenCSV (a comma). Then i read the header and fields
CSVReader reader = null;
try {
if (delimiter > 0) {
reader = new CSVReader(new FileReader(this.csvFile), this.delimiter);
}
else {
reader = new CSVReader(new FileReader(this.csvFile));
}
// these should be the header fields
header = reader.readNext();
while ((fields = reader.readNext()) != null) {
// more code
}
catch (IOException e) {
System.err.println(e.getMessage());
}