rishiag rishiag - 6 months ago 40
Java Question

How to read comma separated values from text file in JAVA?

I have got this text file with latitude and longitude values of different points on a map. I want to store these coordinates into a mySQL database using hibernate. I want to know 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, tab etc.?
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
28.510530488025346,77.38720178604126
28.509615992924807,77.38790988922119
28.50875805732363,77.38862872123718
28.507994394490268,77.38943338394165
28.50728729434496,77.39038825035095
28.506674470385246,77.39145040512085
28.506174780521828,77.39260911941528
28.505665660113582,77.39376783370972
28.505156537248446,77.39492654800415
28.50466626846366,77.39608526229858
28.504175997400655,77.39724397659302
28.503685724059455,77.39840269088745
28.503195448440064,77.39956140518188
28.50276174118543,77.4007523059845
28.502309175192945,77.40194320678711
28.50185660725938,77.40313410758972
28.50140403738471,77.40432500839233
28.500951465568985,77.40551590919495
28.500498891812207,77.40670680999756
28.5000463161144,77.40789771080017
28.49959373847559,77.40908861160278


Code I am using to read from file:

try {
BufferedReader in = new BufferedReader(new FileReader("G:\\RoutePPAdvant2.txt"));
String str;
str = in.readLine();
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}

AVD AVD
Answer

You may use the String.split() method:

String[] ar=str.split(",");

After that, use Double.parseDouble () method to parse the string value to double.

double latitudes=Double.parseDouble(ar[0]);
double longitudes=Double.parseDouble(ar[1]);