I have got this text file with latitude and longitude values of different points on a map.
How can I split my string into latitudes and longitudes? What is the general way to do these type of things that is with other delimiters like space or tab etc.? Sample file:
28.515046280572285,77.38258838653564
28.51430151808072,77.38336086273193
28.513566177802456,77.38413333892822
28.512830832397192,77.38490581512451
28.51208605426073,77.3856782913208
28.511341270865113,77.38645076751709
This is the code I am using to read from the file:
try(BufferedReader in = new BufferedReader(new FileReader("C:\\test.txt"))) {
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e) {
System.out.println("File Read Error");
}
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With