How to read comma separated values from text files in Java?

I have this text file, which contains the latitude and longitude values of different points on the map

How do I divide my strings into latitude and longitude? What is the general way to perform these types of things with other separators, such as spaces or tabs? 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 use 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");
}

Solution

You can use string Split() method:

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

After that, use double The parsedouble () method parses the string value to double

double latitude = Double.parseDouble(tokens[0]);
double longitude = Double.parseDouble(tokens[1]);

Similar parsing methods exist in other wrapper classes - integer, Boolean, etc

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>