如何从Java中的文本文件中读取逗号分隔值? [英] How can I read comma separated values from a text file in Java?

查看:489
本文介绍了如何从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() 将字符串值解析为double的方法。

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 布尔值等。

Similar parse methods exist in the other wrapper classes as well - Integer, Boolean, etc.

这篇关于如何从Java中的文本文件中读取逗号分隔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆