如何从 Java 中的文本文件中读取逗号分隔值? [英] How can I read comma separated values from a text file in Java?
问题描述
我有这个文本文件,其中包含地图上不同点的纬度和经度值.
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");
}
推荐答案
您可以使用 String.split()
方法:
You may use the String.split()
method:
String[] tokens = str.split(",");
之后,使用 Double.parseDouble()
方法将字符串值解析为双精度值.
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]);
其他包装类中也存在类似的解析方法 - Integer
、Boolean
等
Similar parse methods exist in the other wrapper classes as well - Integer
, Boolean
, etc.
这篇关于如何从 Java 中的文本文件中读取逗号分隔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!